Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript 'strict mode' not working as expected?

var test = function() {

    'use strict';

    var mapNames = {
        'name': 'City Name:',
        'coord.lat': 'Latitute:'
    };  

    for (var key in mapNames) {

        var names;

        if (mapNames[key]) {
            name = mapNames[key];
        } else {
            name = key;
        }
    }

    console.log(name);

}

test();

In the code above I made a mistake by declaring variable names and using name instead. I thought 'strict' mode would catch it but it didn't. Shouldn't this throw an error in this case?

like image 705
JS-JMS-WEB Avatar asked Jun 28 '15 11:06

JS-JMS-WEB


People also ask

What is correct way to run a JavaScript in strict mode?

Using Strict mode for a function: Likewise, to invoke strict mode for a function, put the exact statement “use strict”; (or 'use strict';) in the function's body before any other statements. Examples of using Strict mode: Example: In normal JavaScript, mistyping a variable name creates a new global variable.

Should you use strict mode JavaScript?

First, all of your code absolutely should be run in strict mode. Core modern javascript functionality is changed (see . call() and apply()) or disfigured (silent Errors) by executing code outside of strict mode.

What is not allowed in strict mode?

Not Allowed in Strict Mode Objects are variables too. Deleting a variable (or object) is not allowed. Deleting a function is not allowed. For security reasons, eval() is not allowed to create variables in the scope from which it was called.

Why is this undefined in strict mode?

In strict mode, it is now undefined . When a function was called with call or apply , if the value was a primitive value, this one was boxed into an object (or the global object for undefined and null ). In strict mode, the value is passed directly without conversion or replacement.


1 Answers

A name global variable already exists, unrelated to your code; it represents the name of the current window, so you are assigning to an already existing variable.

window.name; // the name of the current window for cross-window communication

Everything on window is declared as a global - so it is not reference-erroring since it is assigning to a variable in an outer scope.

Super confusing :D

  • window.name on MDN.
  • HTML Specification, window name property.

"use strict" would prevent defining new global variables, here we are performing an assignment to an existing variable, think of it as name is in the global scope, like window.Blob, window.console and so on.

like image 82
Benjamin Gruenbaum Avatar answered Oct 04 '22 17:10

Benjamin Gruenbaum