When to Use Strict Mode in JavaScript

This post is work-in-progress learning-note and still in active development and updated regularly.

JavaScript, since introduced in 1995, has been evolving without much compatibility issues and standardized script rules. In ECMAScript 5 (ES5), new features, syntax rules including Strict Mode feature were added in the language.

In MDN, Strict Mode  is referred as a way to opt in to a restricted variant of JavaScript and opting out of of “sloppy mode“. Strict mode follows different code semantics. Strict mode modifies several normal code semantics:

  • Eliminates some JS silent errors by changing them to throw errors.
  • Fixes mistakes that make it difficult for JS engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that’s not strict mode.
  • Prohibits some syntax likely to be defined in future versions of ECMAScript.
How to Declare Strict Mode

Strict mode is invoked by adding "use strict" or 'use strict' before any statement (at the top). It applies to entire script or individual functions but does not apply to block statements enclosed in { } braces.

1. Use Example in Script
// strict mode syntax in script
'use strict';
let greeting = "An example of strict mode use in script!";

console.log(greeting);

//OUTPUT
An example of strict mode use in script!

The MDN highlights some pitfall of using ‘use strict’ in scripts.

2. Use Example in Function

To invoke Strict mode in function add “use strict”; or ‘use strict’; in the function’s body before any other statements.

//Strict mode syntax in function
function greeting() {
  // Function-level strict mode syntax
  'use strict';
  function sayHi() { 
    return 'And so am I!'; 
   }
  return "Hi!  I'm a strict mode function!  " + sayHi();
 }

//invoke function
greeting();

//OUTPUT
"Hi!  I'm a strict mode function!  And so am I!"

//Function w/o strict mode
function welcome() {
  return "I'm not in strict mode."; 
  }
welcome();

//OUTPOT
"I am not in strict mode."

Tip: There is no way to cancel "use strict" directive once it is invoked. There is no return.

Changes in Strict Mode

Use of 'strict mode' modifies both the syntax and runtime behavior. More detailed information are available in Mozilla Development Network.

Browser Support for Strict Mode

Most modern browser support strict mode. However, it is advised to test in browsers before use. For more information about browser compatibility refer this comprehensive ECMAScript Compatibility Table on GitHub before use.

Resources & Further Reading:

While preparing this post, I have referred the following references extensively. Please to refer original posts for more detailed information.