4

Possible Duplicate:
Is there a standard function to check for null, undefined, or blank variables in JavaScript?

What is the best way to check undefined type in javascript. I know 1 way to check for undefined type i.e. typeOf. But i have to check if for lots of places, so if there is any short and better way to check then please let me know ?

I tried few ways but did`nt get success :

    alert(undefined === "undefined");
    alert(undefined || "defined"); 
Community
  • 1
  • 1
Tom Rider
  • 2,497
  • 7
  • 38
  • 61

4 Answers4

8

Nothing new for you:

// either
(val === undefined)
// or
(typeof val == "undefined")

The problem of using val || "defined" is that "defined" will be returned in case val is null, undefined, 0, false or "".

VisioN
  • 132,029
  • 27
  • 254
  • 262
1

That is the best way what you said using typeof.

Example:

alert(typeof variable === 'undefined')
Snake Eyes
  • 14,643
  • 31
  • 97
  • 188
  • `typeof` always returns string, so there is no special need for `===`. – VisioN Oct 19 '12 at 12:06
  • 2
    Yes, no special needs but I am in safe with that. I want to compare strictly the strings, no more conversion, I know that `typeof` returns string. – Snake Eyes Oct 19 '12 at 12:07
  • 3
    @VisioN `===` is marginally faster than `==`, so it is actually preferred. – John Dvorak Oct 19 '12 at 12:11
  • @JanDvorak I've made a [jsperf](http://jsperf.com/2eq-vs-3eq) to check. My results are different each new test run (Chrome 22). – VisioN Oct 19 '12 at 12:18
  • @VisioN It looks equal to within statistical error. Thanks – John Dvorak Oct 19 '12 at 12:32
  • @VisioN it's better to pretend `==` doesn't exist. – jbabey Oct 19 '12 at 12:39
  • 1
    @jbabey—given javascript's loose typing, `==` is very handy, e.g. `1 == '1'`. Imagine having to cast everything to the same Type before doing comparisons (which is more-or-less what `==` does anyway). I prefer to only use `===` where necessary and use `==` everywhere else. – RobG Oct 19 '12 at 12:44
0

Using typeof val == "undefined" is the best way since the value of undefined can be modified.

var x;

console.log("x == undefined => " + (x == undefined));
console.log("typeof x == 'undefined' => " + (typeof x == 'undefined'));

var undefined = 10; // for some reason, browsers allow this!
console.log('undefined overwritten to ' + undefined);

console.log("x == undefined => " + (x == undefined)); // this will return false!
console.log("typeof x == 'undefined' => " + (typeof x == 'undefined'));
techfoobar
  • 61,046
  • 13
  • 104
  • 127
  • 1
    In ES5, the [`undefined`](http://ecma-international.org/ecma-262/5.1/#sec-15.1.1.3) property of the global object is read only, so you can't set its value to anything else. – RobG Oct 19 '12 at 12:40
-1
var variable2 = variable1  || '';

If Variable 1 is undefined, it'll set it to '', else, it'll use variable1.

Daniel Noel-Davies
  • 537
  • 1
  • 5
  • 10