In "non-strict"
mode of javascript, We can assign value to undefined
. I tried to assign it value but when I tried to print that value it's giving me strange results.
let a = 10;
undefined = 20;
a = undefined;
console.log(a); // undefined not 20
console.log(undefined); // undefined not 20
If I create my own scope then undefined
can be overwritten. I know that since ECMA 5 you cannot override undefined
it's read-only. Then how I am getting the following output(set undefined to 10) for my own scope?
Does it means that I can write that in my own scope(non-global) only?
(function (undefined) {
undefined = 10;
console.log("Value of undefined: " + undefined);
})();
This is as expected. References to undefined
is actually window.undefined
, and the undefined
property of window
is non-writable:
console.log(Object.getOwnPropertyDescriptor(window, 'undefined'));
And non-writable properties can't be overwritten.
The difference is that in strict mode, trying to write to it throws an error, whereas in sloppy mode, the failure is silent.
The same sort of behavior can be seen if you assign another non-writable property to window
and try to overwrite it:
Object.defineProperty(window, 'prop', { value: 'value', writable: false });
window.prop = 5;
console.log(window.prop);
(() => {
'use strict';
window.prop = 10;
})();
Although You Don't Know JS says you can "assign a value to the globally provided undefined identifier", this is only true for ES3 environments and below. In ES5+ (which pretty much all browsers support nowadays), undefined
is not overwritable.