Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

What does this line below do?

undefined = 'A value';

If it does not change the value of undefined then what happens behind the scenes?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
152 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...