// applies strict mode to the current and child scopes
function(){
"use strict"; // invokes strict mode
console.log( "in strict mode" );
function(){
console.log( "also in strict mode" );
}
}
// out of scope
console.log( "NOT in strict mode" );
Invoking Strict Mode
// accidentally defining a variable in the global scope
foo = "bad"; // forgot to use the var keyword
// no errors are thrown
global.foo; // bad
"use strict";
// accidentally defining a variable in the global scope
foo = "bad"; // forgot to use the var keyword
// throws ReferenceError: foo is not defined
"use strict";
var foo = "good";
var foo = 1;
fuu = 2; // typo
foo; // 1, oops!
global.fuu; // 2, pollution!
"use strict";
var foo = 1;
fuu = 2; // typo
// throws ReferenceError: fuu is not defined
// normal mode allows duplicate keys in objects
var favorites = {
starWars : "episode 6",
starWars : "episode 1"
}
favorites.starWars; // ??
"use strict";
var favorites = {
starWars : "episode 6",
starWars : "episode 1"
// SyntaxError: Duplicate data property in object
// literal not allowed in strict mode
}
// exited due to error
ECMAScript6 keywords are now reserved words
prohibits function statements not at the top level of a script or function
"use strict";
if (true){
function foo() { }
// SyntaxError: In strict mode code, functions can only be declared
// at top level or immediately within another function.
foo(); // program exited
}
for (var i = 0; i < 5; i++){
function bar() { }
// SyntaxError: In strict mode code, functions can only be declared
// at top level or immediately within another function.
bar(); // program exited
}
function baz(){ // ok
function qux() { } // ok
function norf() { } // ok
}