What happens if we set the value of undefined?

前端 未结 3 1610
忘了有多久
忘了有多久 2020-12-10 10:04

What does this line below do?

undefined = \'A value\';

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

3条回答
  •  渐次进展
    2020-12-10 10:40

    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
    

提交回复
热议问题