Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to check if a global variable exists?

JSLint is not passing this as a valid code:

/* global someVar: false */ if (typeof someVar === "undefined") {     var someVar = "hi!"; } 

What is the correct way?

like image 449
Ebrahim Byagowi Avatar asked Jul 21 '12 22:07

Ebrahim Byagowi


People also ask

How do I check if a global variable exists?

To check if a global variable exists in Python, use the in operator against the output of globals() function, which has a dictionary of a current global variables table. The “in operator” returns a boolean value. If a variable exists, it returns True otherwise False.

How do you check if a variable exists?

Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined.

How do you indicate that a variable is a global variable?

Variables that are created outside of a function (as in all of the examples above) are known as global variables. Global variables can be used by everyone, both inside of functions and outside.

How do I check if a variable exists in Python?

To check the existence of a local variable: if 'myVar' in locals(): # myVar exists. To check the existence of a global variable: if 'myVar' in globals(): # myVar exists.


2 Answers

/*global window */  if (window.someVar === undefined) {     window.someVar = 123456; }  if (!window.hasOwnProperty('someVar')) {     window.someVar = 123456; } 
like image 77
bigoldbrute Avatar answered Sep 28 '22 10:09

bigoldbrute


/**  * @param {string} nameOfVariable  */ function globalExists(nameOfVariable) {     return nameOfVariable in window } 

It doesn't matter whether you created a global variable with var foo or window.foo — variables created with var in global context are written into window.

like image 42
gvlasov Avatar answered Sep 28 '22 10:09

gvlasov