Basically two questions, both pertaining to the behavior of undefined.
Q1 Why is it that this fails with a reference error:
function hello(a){
return true;
}
//var abc = undefined;
hello(abc);
but this doesn’t:
function hello(a){
return true;
}
var abc = undefined;
hello(abc);
Q2 Why is it that this is a valid assignment:
undefined = 10;
But these aren’t:
null = 10;
"hello" = 10;
10 = 10;
Thanks for your help.
In the first case you are not defining the key
'abc'on the global object and thus you are having a reference error trying to access it. It is something like'Name error'in ruby and python saying that an identifier isundefined.These two are equivalent and they both define the
'abc'key on the global object, in your case this iswindow.Defining undefined as an identifier works. It defines the window.undefined key not the undefined type. This means that:
In order to perform undefined check, check the type of the identifier:
Because:
In addition undefined is not a primitive. While
0,'string'are primitives.nullis a special singleton object as pointed out in the comments. Those are not identifiers but actual values so you cannot assign to them by specification.Update regarding NaN:
NaN is slightly different because it is a primitive (number). Trying to do the same with NaN yeilds: