Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a variable exists in javascript

Tags:

javascript

I know there are two methods to determine if a variable exists and not null(false, empty) in javascript:

1) if ( typeof variableName !== 'undefined' && variableName )

2) if ( window.variableName )

which one is more preferred and why?

like image 676
Kirill Ivlev Avatar asked May 23 '13 16:05

Kirill Ivlev


People also ask

How do you check if a variable exists?

Answer: Use the typeof operator If you want to check whether a variable has been initialized or defined (i.e. test whether a variable has been declared and assigned a value) you can use the typeof operator.

How check variable is empty or not in JavaScript?

Say, if a string is empty var name = "" then console. log(! name) returns true . this function will return true if val is empty, null, undefined, false, the number 0 or NaN.

How do you check if a variable is not defined?

To check if a variable is undefined, you can use comparison operators — the equality operator == or strict equality operator === . If you declare a variable but not assign a value, it will return undefined automatically. Thus, if you try to display the value of such variable, the word "undefined" will be displayed.

How do you check if a variable is defined in typescript?

We can use typeof or '==' or '===' to check if a variable is null or undefined in typescript.


1 Answers

A variable is declared if accessing the variable name will not produce a ReferenceError. The expression typeof variableName !== 'undefined' will be false in only one of two cases:

  • the variable is not declared (i.e., there is no var variableName in scope), or
  • the variable is declared and its value is undefined (i.e., the variable's value is not defined)

Otherwise, the comparison evaluates to true.

If you really want to test if a variable is declared or not, you'll need to catch any ReferenceError produced by attempts to reference it:

var barIsDeclared = true;  try{ bar; } catch(e) {     if(e.name == "ReferenceError") {         barIsDeclared = false;     } } 

If you merely want to test if a declared variable's value is neither undefined nor null, you can simply test for it:

if (variableName !== undefined && variableName !== null) { ... } 

Or equivalently, with a non-strict equality check against null:

if (variableName != null) { ... } 

Both your second example and your right-hand expression in the && operation tests if the value is "falsey", i.e., if it coerces to false in a boolean context. Such values include null, false, 0, and the empty string, not all of which you may want to discard.

like image 168
apsillers Avatar answered Oct 02 '22 16:10

apsillers