Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle 'undefined' in JavaScript [duplicate]

Tags:

javascript

Possible Duplicate:
Detecting an undefined object property in JavaScript

From the below JavaScript sample,

try {     if(jsVar) {         proceed();     } } catch(e) {     alert(e); } 

this jsVar is declared and initialized in another file.

The problem is that code throws undefined error when this code is executed before the other file (where its declared and initialized) is executed. That is why it is surrounded by try and catch.

What's the best way to handle this undefined error than try catch?

like image 859
Madhu Avatar asked Dec 31 '09 09:12

Madhu


People also ask

How do you handle undefined value in JavaScript?

myVariable is declared and not yet assigned with a value. Accessing the variable evaluates to undefined . An efficient approach to solve the troubles of uninitialized variables is whenever possible assign an initial value. The less the variable exists in an uninitialized state, the better.

Does undefined === false?

The Boolean value of undefined is false.

Is undefined === undefined in JS?

typeof variable === “undefined” in JavaScript. Undefined comes into a picture when any variable is defined already but not has been assigned any value. Undefined is not a keyword. A function can also be undefined when it doesn't have the value returned.

Why do I keep getting 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

You can check the fact with

if (typeof jsVar == 'undefined') {   ... } 
like image 200
alex.zherdev Avatar answered Sep 20 '22 11:09

alex.zherdev


As is often the case with JavaScript, there are multiple ways to do this:

typeof foo !== 'undefined' window.foo !== undefined 'foo' in window 

The first two should be equivalent (as long as foo isn't shadowed by a local variable), whereas the last one will return true if the global varible is defined, but not initialized (or explicitly set to undefined).

like image 41
Christoph Avatar answered Sep 22 '22 11:09

Christoph