use-strict in JavaScript

  • Introduced in, 2009 with ECMAScript 5 (ES5),
  • A way to determine your JavaScript runs in "sloppy mode" or "strict mode"
  • Strict mode changes some previously-accepted mistakes into errors.
  • JavaScript allowed some error-prone ways of writing code, eg:
    - declaring variables without let, const or var,
    - function parameters with same name
    - adding properties to primitive values
    - NaN is a non-writable global variable. In sloppy mode, assigning to NaN does nothing; the developer receives no failure feedback. In strict mode, assigning to NaN throws an exception.

"use-strict" in JavaScript

"use strict";

false.true = ""; // TypeError
(14).sailing = "home"; // TypeError
"with".you = "far away"; // TypeError


// Assignment to a non-writable global
undefined = 5; // TypeError
Infinity = 5; // TypeError

delete Object.prototype; // TypeError
delete [].length; // TypeError
  • Strict mode applies to entire scripts (file) or to individual functions.
  • It doesn't apply to block statements enclosed in ({}) braces;
  • classes” and “modules” – enable use strict automatically. So we don’t need to add the "use strict" directive, if we use them.

"use-strict" in JavaScript


function myStrictFunction() {
  // Function-level strict mode syntax
  "use strict";
  function nested() {
    return "And so am I!";
  }
  return `Hi! I'm a strict mode function! ${nested()}`;
}