Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for an undefined or null variable in JavaScript?

We are frequently using the following code pattern in our JavaScript code

if (typeof(some_variable) != 'undefined' && some_variable != null) {     // Do something with some_variable } 

Is there a less verbose way of checking that has the same effect?

According to some forums and literature saying simply the following should have the same effect.

if (some_variable) {     // Do something with some_variable } 

Unfortunately, Firebug evaluates such a statement as error on runtime when some_variable is undefined, whereas the first one is just fine for it. Is this only an (unwanted) behavior of Firebug or is there really some difference between those two ways?

like image 407
Tomas Vana Avatar asked Apr 01 '10 09:04

Tomas Vana


People also ask

Is undefined or null JavaScript?

Difference Between undefined and null Though, there is a difference between them: undefined is a variable that refers to something that doesn't exist, and the variable isn't defined to be anything. null is a variable that is defined but is missing a value.

How do you check if a variable is not defined in JavaScript?

Summary. In JavaScript, a variable can be either defined or not defined, as well as initialized or uninitialized. typeof myVar === 'undefined' evaluates to true if myVar is not defined, but also defined and uninitialized. That's a quick way to determine if a variable is defined.

Can we check undefined in JavaScript?

If it is undefined, it will not be equal to a string that contains the characters "undefined", as the string is not undefined. You can check the type of the variable: if (typeof(something) != "undefined") ...

Is null == undefined?

It means null is equal to undefined but not identical. When we define a variable to undefined then we are trying to convey that the variable does not exist . When we define a variable to null then we are trying to convey that the variable is empty.


2 Answers

I think the most efficient way to test for "value is null or undefined" is

if ( some_variable == null ){   // some_variable is either null or undefined } 

So these two lines are equivalent:

if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {} if ( some_variable != null ) {} 

Note 1

As mentioned in the question, the short variant requires that some_variable has been declared, otherwise a ReferenceError will be thrown. However in many use cases you can assume that this is safe:

check for optional arguments:

function(foo){     if( foo == null ) {...} 

check for properties on an existing object

if(my_obj.foo == null) {...} 

On the other hand typeof can deal with undeclared global variables (simply returns undefined). Yet these cases should be reduced to a minimum for good reasons, as Alsciende explained.

Note 2

This - even shorter - variant is not equivalent:

if ( !some_variable ) {   // some_variable is either null, undefined, 0, NaN, false, or an empty string } 

so

if ( some_variable ) {   // we don't get here if some_variable is null, undefined, 0, NaN, false, or "" } 

Note 3

In general it is recommended to use === instead of ==. The proposed solution is an exception to this rule. The JSHint syntax checker even provides the eqnull option for this reason.

From the jQuery style guide:

Strict equality checks (===) should be used in favor of ==. The only exception is when checking for undefined and null by way of null.

// Check for both undefined and null values, for some important reason.  undefOrNull == null; 

EDIT 2021-03:

Nowadays most browsers support the Nullish coalescing operator (??) and the Logical nullish assignment (??=), which allows a more concise way to assign a default value if a variable is null or undefined, for example:

if (a.speed == null) {   // Set default if null or undefined   a.speed = 42; } 

can be written as any of these forms

a.speed ??= 42; a.speed ?? a.speed = 42; a.speed = a.speed ?? 42; 
like image 186
mar10 Avatar answered Oct 03 '22 10:10

mar10


You have to differentiate between cases:

  1. Variables can be undefined or undeclared. You'll get an error if you access an undeclared variable in any context other than typeof.
if(typeof someUndeclaredVar == whatever) // works if(someUndeclaredVar) // throws error 

A variable that has been declared but not initialized is undefined.

let foo; if (foo) //evaluates to false because foo === undefined 
  1. Undefined properties , like someExistingObj.someUndefProperty. An undefined property doesn't yield an error and simply returns undefined, which, when converted to a boolean, evaluates to false. So, if you don't care about 0 and false, using if(obj.undefProp) is ok. There's a common idiom based on this fact:

    value = obj.prop || defaultValue 

    which means "if obj has the property prop, assign it to value, otherwise assign the default value defautValue".

    Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the in operator instead

    value = ('prop' in obj) ? obj.prop : defaultValue 
like image 25
user187291 Avatar answered Oct 03 '22 12:10

user187291