How Strict Is “use strict” In JavaScript ?

Published On: 20 Jul, 2015 Updated On: 21 Apr, 2017

JavaScript has been always magical. And you too will believe it when you come to know that it has two different modes of execution. What I say by mode is that JavaScript has two different variants. One is ‘normal’ and another is ‘restricted’. In this article, we’ll study in-depth about how restricted variant of JavaScript is written, how browsers execute this variant, security concerns and performance overhead of normal JavaScript code and how we can use this restricted variant to improve security and performance. So.. let’s start!

The Restricted Variant Of JavaScript

ECMAScript 5 provides web developers a nice way of writing restricted variant of JavaScript code. Strict mode can be invoked just by including below statement.


"use strict";

Strict mode applies to entire scripts or to individual functions. It doesn’t apply to block statements enclosed within braces. Attempting to apply it to such contexts doesn’t change anything. Let’s take a look at below code to understand the meaning of this statement.

/**
 * Lets say below line as 'STATEMENT-1'
 */
// "use strict";

function personFactory( name, designation ) {
  Object.defineProperties( this, {
    name : {
      value : name,
      writable : true
    },
    designation : {
      value : designation,
      writable : false
    }
  } );
};

if( typeof personFactory == 'function' ) {
  "use strict";
  var santosh = new personFactory( 'Santosh', 'Web Developer' );

  /**
   * Even though we have "use strict" statement within 'if' block statement
   * and santosh.designation is read-only,
   * "delete santosh.designation" doesn't throw any errors.
   * This tells us that there is no change of adding "use strict" in block statements.
   * However, if you clear commented part of 'STATEMENT-1' above,
   * browser will start throwing errors.
   */
  delete santosh.designation;
}

If you’re migrating your normal code to strict mode, it’s better you move incrementally by placing “use strict” within functions. Otherwise, as I noted above, “use strict” at global scope will apply universally to all places and may break entire code at any point.
Browsers supporting Strict mode run differently compared to the browsers that don’t support Strict mode. So, without feature testing, don’t rely on Strict mode blindly. It may make your code break anytime. For browser compatibility, check out here.

How Browsers Treat Strict Mode ?

Whenever browser engines understands that the code is a restricted variant of JavaScript, they make some necessary optimizations to run the code faster, error free and secure. Below are some of the changes browser engines do.

  1. Buggy code that runs silently in normal mode are now converted such that they throw respective errors.
  2. Helps JavaScript engines to improve run-time execution performance by fixing run-time decisions.

Strict Mode Syntax And Runtime Behavioral Changes

Following are some of the changes browser engines perform for JavaScript Strict mode.

  1. Mistakes are converted into errors (either syntax or run-time).
  2. Changes that help in writing secure JavaScript code.

Now, let’s discuss how each of the above mentioned changes work.

1. Mistakes are converted into errors (either syntax or run-time)

Many times, we accidentally declare variables without ‘var’ keyword (which makes them global), try to change or delete variables and properties which are read-only, pass duplicate arguments and so on.. Strict mode converts all these kind of mistakes into errors so that developers write error free code.

First, Strict mode makes it impossible to create accidental global variables. Let’s take a look at below code to understand the real meaning of it.

Normal variant code:-

function sum() {
  total = 0;

  for( i = 0; i < arguments.length; i++ ) {
    total += arguments[i];
  }

  console.log(total);
};

sub( 1, 2, 4 );

/**
 * Above normal variant code runs perfectly. But there is a problem here.
 * There are two accidentally defined global variables ( 'total' and 'i' ).
 * Since, 'var' is not mandatory in normal JavaScript mode, no errors are thrown.
 */

Strict variant code:-


"use strict";

function sum() {
  total = 0;

  for(i = 0; i < arguments.length; i++) {
    total += arguments[i];
  }

  console.log(total);
};

sub( 1, 2, 4 );

/**
 * Above Strict variant code throws error and stops execution.
 * This is because within methods, globals are getting created.
 */

Updated strict variant code:-

/**
 * Only way to make the above Strict mode code work is
 * by declaring those globals as locals as given in updated code below.
 */
"use strict";

function sum() {
  var total = 0;

  for(var i = 0; i < arguments.length; i++) {
    total += arguments[i];
  }

  console.log(total);
};

// This now works just as normal mode works, but no globals. Great!
sub( 1, 2, 4 );

Second, JavaScript has few reserved constants like “NaN” which are read-only. In normal mode, if someone tries to assign value to such constants, no errors are thrown. Code runs silently. But, in Strict mode, errors are thrown saying you can’t change read-only properties. You can’t even delete such properties. Remember ‘NOTE-1’ we discussed at the beginning ?

Third, Strict mode throws error when duplicate arguments are passed to functions. Passing duplicate parameters is a Syntax error in JavaScript Strict mode. Let’s take a look at below code to understand the meaning of it.


"use strict";

/**
 * Normal mode runs silently without any errors.
 * But in Strict mode, error is thrown and execution is stopped.
 * Please note that this is compile time error in Strict mode.
 */
function personFactory(name, designation, address, name) {
  this.name = name;
  this.designation = designation;
  this.address = address;
};

/**
 * In normal mode, last duplicate parameter hides all previous parameters.
 * Value accessed by param name would return the last duplicate param.
 * E.g., in the below code, santosh.name would be 'Bantosh' instead of 'Santosh'.
 * This is because of the duplicate parameter 'name' passed to personFactory method definition.
 */
var santosh = new personFactory('Santosh', 'Web Dev', 'XYZ', 'Bantosh');

2. Changes that help in writing secure JavaScript code

Since JavaScript runs on client browser, there are many security risks that may pose problems of certain degree like private information theft etc. So, it’s required that the code should run in strict mode to block access to forbidden data. Making run-time checks in such cases has some performance cost, hence Strict mode became popular. Below are few of the use cases where Strict mode come in handy.

First, in normal mode, when we use “this” keyword, it’s always referred to as some object. In other words, “this” is either some context specific object or global object. This is a security hazard, since global object provides access to functionality that secure JavaScript environments must restrict. Also, normal mode have to make many of the run-time decisions in order to bind certain value to “this” object. This can become a performance overhead if code is poorly written.

Strict mode helps in solving these problems by assigning “this”, a default value called “undefined”. If we provide value of “this” explicitly, then only “this” is bound to provided value, otherwise it’s “undefined” always. Thus, JavaScript is made secure as well as performance overhead is removed. Let’s take a look at below code to understand how this works.


"use strict";

function fun() {
  return this;
};

/**
 * Below line logs true because, now,
 * 'this' is assigned as undefined by default in Strict mode.
 */
console.log(fun() === undefined);

/**
 * For below calls, 'this' will be updated to use first argument passed.
 * i.e. 'this' would be either Number or Boolean or Null or Undefined etc.
 */
console.log(fun.call(2) === 2);
console.log(fun.apply(null) === null);
console.log(fun.call(undefined) === undefined);
console.log(fun.bind(true)() === true);

Second, in JavaScript normal mode, one can walk along the call stack via commonly implemented extensions to ECMAScript. This has certain degree of insecurity as we can obtain the method name and arguments passed to a method using ‘.caller’ and ‘.arguments’ properties. Strict mode blocks this kind of feature and converts it into run-time errors. Let’s take a look at below code to understand what happens when we try to execute such code.

Normal variant code:-


function calledMethod() {
  console.log(calledMethod.caller);
  console.log(calledMethod.arguments);
};

function callerMethod() {
  calledMethod();        // Logs 'function callerMethod()' and []
  calledMethod(1,2,3,4); // Logs 'function callerMethod()' and [1, 2, 3, 4]
};

callerMethod();

Strict variant code:-

"use strict";

function calledMethod() {
  console.log(calledMethod.caller);
  console.log(calledMethod.arguments);
};

function callerMethod() {
  calledMethod();        // Throws TypeError because of Strict mode.
  calledMethod(1,2,3,4); // This is not executed further because we got error for first call itself.
};

callerMethod();

As you can see in the above code, Strict mode hides many of the unsecure properties and methods that ECMAScript provides in order to make JavaScript secure.

Well! That’s it for today. We’ve learnt a lot about “use strict”, how to use it, how it makes our JavaScript secure, how optimizations are made etc. So, let’s start making our JavaScript code secure, performant and error free. Thank you!

Like this blog ? Share it on your favourite social network.
Search powered by Google

Didn’t find what you were looking for? Try here.

Template Monster

Where you can search over 26K+ Premium Templates.

Now, get flat 10% discount by using “b3fbdxkv49mosrt59dsh0dx29” promo-code.

Email NewsLetter

By subscribing, you’ll get access to latest blogs and other resources. Also, whenever there is any new content addition here, you’ll receive those updates directly to your inbox.

NOTE: I’m a strict antispammer. So you don’t have to worry about spams.

This website is designed by keeping modern browsers in mind. Never mind about legacy browsers. It’s high time we upgrade ourselves.

The website and its contents are created, edited and maintained solely by me (Santosh K Shetty). No one else shall possess any kind of resources unless explicitely mentioned.

Some of the Creative Credit goes to FreePik.

Copyright © from Jun 2014 to May 2018

Table  Of  Contents
On this page,