How to check if a Javascript variable is defined before calling it

I use the Cordova GA plugin to track events, but when testing in my browser I keep getting:

ReferenceError: plugin not defined

I tried many ways to check if a plugin was detected, but it still throws this error. How can I correctly check if a plugin has been defined before I call a function?

+4
source share
2 answers

To check if the JavaScript variable is undefined, you can use

if (typeof myVariable === 'undefined') {
  console.log('The variable is undefined.');
}
+5
source

You can simply put a check before running your code:

if (window.plugin) {//I had assume that `plugin` is in global scope
  alert('plugin');
} else {
  alert('no plugin');
}
Run codeHide result

Using typeof

if('undefined' === typeof plugin) {
  alert('no plugin');
} else {
  alert('plugin ...');
}
Run codeHide result
+1
source

Source: https://habr.com/ru/post/1568591/


All Articles