2

Was reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode under the Converting mistakes into errors, and wanted to make a clear example. So I went over to JSFiddle and attempted to see what the 'use strict'; actually achieves. Here is the code:

(() => {
    // Strict mode makes assignments which would otherwise silently fail to throw an exception. 
    'use strict';
    try {
        const undefined = 666; // throws a TypeError
    } catch(error) {
        console.error(error)
    }
    console.log('Is this read?');
})();

https://jsfiddle.net/cvxau3m7/

I was expecting an error to show up in firebug. I must of misunderstood this somehow?

basickarl
  • 37,187
  • 64
  • 214
  • 335

1 Answers1

2

There is nothing wrong with creating a constant called undefined (unless an undefined variable has already been created in the immediate scope).

Your comment says "which would otherwise silently fail", but your code wouldn't do that.

(() => {
    'use strict';
    const undefined = "some value"; 
    console.log("undefined is " + undefined);
})();

The examples you link to redeclare variables in the global scope. They aren't masking them in a narrower scope.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Ah. My example might be flawed, but I was trying to create an example which *does* throw an error if `'use strict';` is declared and which *fails silently* if `use strict;` is absent. (I only took undefined since it was in the documentation as an example) – basickarl Oct 26 '17 at 09:10
  • Indeed. If "const" is removed an exception will be thrown, it's not silent, because nothing is thrown at all. Explanation here: https://stackoverflow.com/questions/8783510/how-dangerous-is-it-in-javascript-really-to-assume-undefined-is-not-overwritte – Koenigsberg Oct 26 '17 at 09:10