var undefined = true;

Posted by Andreas Grech on Stack Overflow See other posts from Stack Overflow or by Andreas Grech
Published on 2010-03-28T19:47:18Z Indexed on 2010/03/28 19:53 UTC
Read the original article Hit count: 368

Filed under:
|
|

I'm doing some experimenting with this malicious JavaScript line: var undefined = true;

Every uninitialized variable in JavaScript has the value of undefined which is just a variable that holds the special value of 'undefined', so the following should execute the alert:

var undefined = true, 
    x;

if (x) {
    alert('ok');
}

But it doesn't, and my question is why?

On further experimentation, I tried the following:

var undefined = true, 
    x = undefined;

if (x) {
    alert('ok');
}

This time, the alert is executed.

So my question is...since in the first snippet x holds undefined (because it is not initialized), why didn't the alert execute? The strange thing is that when explicitly stating that x is undefined (x = undefined), the alert executed...

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about corner-case