Assigning value to undefined in JavaScript
From MDN:
undefined
is a property of the global object; i.e., it is a variable in global scope. The initial value ofundefined
is the primitive valueundefined
.
Hence, you can assign the value to undefined
unlike true
and null
which are reserved keywords. Note that this is the same case with NaN
as well which is again not a reserved keyword and hence, you can assign any value to it.
Just to add more to this, it doesn't matter even if you are assigning a value to undefined
, it will not write to it as it is a readonly property.
Quoting from MDN again.
In modern browsers (JavaScript 1.8.5 / Firefox 4+), undefined is a non-configurable, non-writable property per the ECMAScript 5 specification. Even when this is not the case, avoid overriding it.
Prefer using strict-mode in your JavaScript by declaring "use strict"
at the very top of the file or inside a function to avoid such things. Using something like
"use strict";
undefined = 'test'; //will raise an error, refer to [1]
[1] VM1082:2 Uncaught TypeError: Cannot assign to read only property 'undefined' of object '#'
This is because undefined is not a reserved word in JavaScript, even though it has a special meaning. So it can be assigned a value and the whole statement is valid. Whereas true
and null
are reserved words and can't be assigned values.
For reference: JavaScript Reserved Words