strict mode

Strict Mode

// 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

Strict Mode

  • Silent errors now throw errors
  • Allows the interpreter to perform optimizations
  • Prohibits some syntax that may be defined in future versions of ECMAScript
  • Makes it easier to write "secure" code

Non-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

Strict Mode

"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";

Non-Strict Mode

var foo = 1;
fuu = 2;     // typo
foo;         // 1, oops!
global.fuu;  // 2, pollution!

Strict Mode

"use strict";
var foo = 1;
fuu = 2;  // typo
// throws ReferenceError: fuu is not defined

Non-Strict Mode

// normal mode allows duplicate keys in objects
var favorites = {
  starWars : "episode 6",
  starWars : "episode 1"
}
favorites.starWars;  // ??

Strict Mode

"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

Strict Mode

ECMAScript6 keywords are now reserved words

  • implements
  • interface
  • let
  • package
  • private
  • protected
  • public
  • static
  • yield

Strict Mode

 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
}

strict mode

By Jon Borgonia

strict mode

  • 2,129