JS: Strict Mode

By Xah Lee. Date: . Last updated: .

What is strict mode

JavaScript standard in year 2011 introduced strict mode. From Standard ECMA-262, 5.1 Edition / June 2011, ECMAScriptยฎ Language Specification Annex C: The Strict Mode of ECMAScript

It is a piece of code like this:

"use strict"

added to the beginning of JavaScript source code file, or inside function at top.

This line of string is called directive.

When strict mode is on, the language has slightly different behavior. Strict mode is created to fix some worst warts of JavaScript.

All major browsers since 2013 support strict mode.

What does strict mode do

The tech details of what strict mode do is fairly complex, and is irrelevant to average JavaScript programer. Here's some salient items:

here's JavaScript spec on strict mode.

js strict mode ECMAScript 2015 JBDTV
ECMAScript 2015 ยงAnnex C

How to turn on strict mode

To use strict mode, add to the beginning of your source code this line:

"use strict"

you can also add it to the top of inside a function. When it's inside a function, strict mode applies to the function's body only.

// strict mode just for this function
function myFun() {
  "use strict";
  // code here

๐Ÿ’ก TIP: i do not recommend adding strict mode to function. It makes things too complex. Just add it to top of all JavaScript files.

Should You Turn on Strict Mode?

Yes, in general. Especially in a big company where lots codes are written by bad coders.

How to test if you are in strict mode?

when a function is called as a function in global context, that is, not as a method of a object, then, the value of this keyword inside the function is different depending on whether it's strict mode or not.

[see this Binding]

// determine if in strict mode

"use strict" // comment this line out to test

function isStrict () { if ( this === undefined ) { return true; } else {return false; } };

console.log (isStrict());
BUY ฮฃJS JavaScript in Depth