Var undefined = true;

I am experimenting with this malicious JavaScript string: var undefined = true;

Each uninitialized variable in JavaScript has an undefined value, which is simply a variable that contains the special value 'undefined' , so the following should execute alert :

 var undefined = true, x; if (x) { alert('ok'); } 

But this is not so, and my question is why?

In further experiments, I tried the following:

 var undefined = true, x = undefined; if (x) { alert('ok'); } 

This time alert is executed.

So my question is ... because the first fragment of x contains undefined (because it is not initialized), why didn’t it execute the alert ? The strange thing is that when I explicitly declare that x is undefined ( x = undefined ), an alert is executed ...

+7
javascript
source share
3 answers

There is a difference between a variable named undefined and a value of undefined .

 var undefined = true, x; 

In this example, the undefined variable is set to true and x to the value (and not to the variable!) undefined .

 var undefined = true, x = undefined; 

In this example, the undefined variable is also set to true , and x set to the value contained in the undefined variable (which is true ).

So, although you can declare a variable named undefined , you cannot change the fact that uninitialized variables are set to undefined .

+17
source share

Just declaring a variable with the name "undefined" does not mean that you are redefining the built-in concept of what "undefined" is.

Imagine that Java allows you to use "null" as an identifier. Well, I think Java does not have the same compulsion as Javascript. Anyway, the Javascript statement

 if (x) alert("foo"); 

implies implicit coercion of the value of "x" to a logical one. The value is undefined, so forcing it to "boolean" results in false .

+1
source share

Uninitialized variables receive the special value undefined . When you assign a variable to another variable, you give it a string that refers to the variable that you defined in the current scope. In this case, you defined a variable called undefined , so the JavaScript engine will first be scanned through the variables, see, What did you call one undefined , and then assigned it to this variable.

0
source share

All Articles