What happens if we set the value of undefined?

undefined is a property of the global object, i.e. it is a variable in global scope. The initial value of undefined is the primitive value undefined.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined

So, it’s just a variable, nothing special about it. Now, to answer your questions:

  1. undefined = 'A value'; attempts to assign a string 'A value' to the global variable undefined
  2. In older browsers the value changes, i.e. undefined === 'A value'; // true. In newer browsers under strict mode the operation results in an error.

You can test the following in a browser console (I’m using a modern browser here – Google Chrome):

undefined = true;
console.log(undefined); // undefined
// in older browsers like the older Internet Explorer it would have logged true

The value of undefined doesn’t change in the above example. This is because (emphasis mine):

In modern browsers (JavaScript 1.8.5 / Firefox 4+), undefined is a non-configurable, non-writable property per the ECMAScript 5 specification.

Under strict mode:

'use strict';
undefined = true; // VM358:2 Uncaught TypeError: Cannot assign to read only property 'undefined' of object

Leave a Comment