Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for Undefined in Javascript

I was following the below logic to check if a variable is undefined or not:

 if (variable==undefined){
////implementation
}

But found that for some cases it did not function as expected. So, tried this approach,

if(typeof(variable) == "undefined"){
/////implementation
}

So which one is most reliable?

like image 283
RK- Avatar asked Jun 20 '11 05:06

RK-


People also ask

How do you check if a variable is undefined in JS?

The typeof operator for undefined value returns undefined . Hence, you can check the undefined value using typeof operator. Also, null values are checked using the === operator. Note: We cannot use the typeof operator for null as it returns object .

How do you test for undefined?

Note: The undefined is not a reserved keyword in JavaScript, and thus it is possible to declare a variable with the name undefined. So the correct way to test undefined variable or property is using the typeof operator, like this: if(typeof myVar === 'undefined') .

Is undefined == undefined JavaScript?

Simply put, undefined means a variable has been declared but has not yet been assigned a value. undefined is a type by itself (undefined). Unassigned variables are initialized by JavaScript with a default value of undefined.

How do I get undefined in JavaScript?

You will get undefined value when you call a non-existent property or method of an object. In the above example, a function Sum does not return any result but still we try to assign its resulted value to a variable. So in this case, result will be undefined.


2 Answers

Your second way is the most reliable but you don't need the parenthesis for the typeof operator. See this question.

like image 157
Asaph Avatar answered Sep 21 '22 21:09

Asaph


if (variableName){
////implementation
}

this way is more use full than second option

like image 44
amit kate Avatar answered Sep 23 '22 21:09

amit kate