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?
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.
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.
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.
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.
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."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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With