An easy check for SharePoint Online or on premises would be to look at the host name. In the case of SharePoint Online, it will always be in the form of
tenant.sharepoint.com. A local installation, third party hosted, or something running in Azure, it will be for all intents and purposes the same thing, an on premises installation.
var context = SP.ClientContext.get_current();
serverVersion = clientContext.get_serverVersion();
//do something else
This comes with some risk as I don't really know what you then want to do. For example, running this against my Online tenant says 16.0.5507.1207. This would infer that I'm on 2016, but my site collections are still in 2013 mode, so it may or may not suit your need.