What happens if we set the value of undefined?

前端 未结 3 1602
忘了有多久
忘了有多久 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:45

    I've made a little POC with and without strict mode.

    The effect is that, if you're not using strict mode everything goes fine. If you're using strict mode you'll have a nice:

    TypeError: Cannot assign to read only property 'undefined'

    Now let's get to the POC:

    "use strict"
    var c;
    
    if (c === undefined) {
      console.log("nothing happened")
    }
    
    undefined = "goofy"
    
    c = "goofy"
    
    if (c === undefined) {
      console.log("c is 'goofy' and it's equal to undefined.. gosh.. we broke js")
    }
    

    Now, as I said, with strict mode you obtain a TypeError while removing the "use strict" the script goes fine and the output is simply nothing happened.

    I've found this Q/A that could be useful if you want to know more

    NOTE: I've tested this code using Node.js.

提交回复
热议问题