JavaScript: “use strict” – [strict mode]

use strict” directive enables a strict operating context/mode for the code.

This helps us to identify potential exceptions and makes debugging easier. In strict mode, we are notified about code that would trigger some weird behavior or fail silently.

Note

Strict mode is automatically enabled in JavaScript modules and classes. We don’t need to explicitly enable it.
If we add “use strict” for a module, then the following message is shown-

‘use strict’ is unnecessary inside of modules (strict)

If it is not a JS module or class then we can enable strict mode by using the following methods-

Enable for the whole script

To enable the strict mode for the whole script, add the string “use strict” at the top of the script.

"use strict";

// your code here

Both single and double quotations will work-

'use strict';

// your code here

Make sure to add the “use strictat the top of the script. If it is not at the top, then there will be no effect.

Make sure to use the quotation around the string, as this is not some special keyword.

The “use strict” needs to be in lower case, upper case will not work. So-

Accepted:

  •  “use strict”
  •  ‘use strict’

Not Accepted:

  •  “USE STRICT”
  •  “use STRICT”
  •  “Use strict”

As “use strict” is written as a string, so if this is used in an older browser that does not support this feature, then this line will be ignored. As this is just a string to those old browsers, so it will be ignored.

Enable for a function

We can add the “use strict” inside a function, at the top.

In that case, only the code inside that function will use strict mode. Code outside the function will not be affected by that.

Check the example below-

// Not operating in strict mode

function bigBoxFun() {
    "use strict";

    // Using strict mode

    // Your code here
}

// Not operating in strict mode

This way we can add strict mode to only a specific part of our code, and keep the rest unaffected.

Make sure to add the “use strictat the top of the function. If it is not at the top, then there will be no effect.

Once activated, then there is not way to deactivate the strict mode in the middle of the script or function.

strict mode” Restrictions

When the strict mode is on, the following restrictions are activated-

Restriction #1: Detect undefined variable

Check the code below. Here we have a variable named “bigBoxCode” which has some value.

But later we wanted to change the value, but by mistake, we typed “bigboxcode” (notice the case). As the case is different, so these are 2 different variables.

This would cause confusion and introduce bugs, in the later part of the script.

let bigBoxCode = true;

// Some code here

// Now we want to change the value of "bigBoxCode"
// But we make a spelling mistake and write "bigboxcode"
bigboxcode = false;

// Some code here

// Now we want to write some code that depends on the "bigBoxCode" variable value
console.log(bigBoxCode);

// This will console.log true as "bigBoxCode" value is true
// No exception will be thrown and will have a hard time debugging why the value is true

But, if we use the strict mode, then this will trigger an error as “bigboxcode” is never defined.

"use strict";

let bigBoxCode = true;

// Some code here

// Now we want to change the value of "bigBoxCode"
// But we make a spelling mistake and write "bigboxcode"
bigboxcode = false; // Uncaught ReferenceError: bigboxcode is not defined

// Some code here

// Now we want to write some code that depends on the "bigBoxCode" variable value
console.log(bigBoxCode);

The line “bigboxcode = false;” will trigger an error with message –

Uncaught ReferenceError: bigboxcode is not defined

The full error message looks like below-

This way we can get rid of all the errors related to variables which are not defined.

Restriction #2: Detect restricted keyword

When the script is not in strict mode, then we can use certain keywords(reserved for future use) as variable name. See the example below, we are able to use the ‘let’ as variable name, and no exception will be thrown.

var let = 3;
var interface = 100;

console.log(let, interface);
// logs 3 100  in the console

This would be problematic in the future. So it is better to restrict these types of usage.

Using strict mode we can restrict these restricted keyword usage for different purposes. Check the code below-

"use strict";

var let = 3; // Throws error in strict mode
var interface = 100; // Throws error in strict mode

console.log(let, interface);

It will throw an exception with the message-

Uncaught SyntaxError: Unexpected strict mode reserved word

In the console, the error looks like the image below-

All the following keywords are restricted for variable name usage, in strict mode-

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

Restriction #3: Prevent global read-only property reassignment

If the strict mode is not enabled then we can write code to reassign global properties like NaN, undefined etc.

NaN = 99;
undefined = 99;

console.log(NaN, undefined);
// logs - NaN undefined

Though the values are not changed, but this code causes confusion.

Better to use strict mode, which throws an error when we try to reassign these read-only properties-

"use strict";

NaN = 99; // Throws error
undefined = 99; // Throws error

console.log(NaN, undefined);

The above code, where we are trying to reassign throws errors with messages-

Uncaught TypeError: Cannot assign to read only property ‘NaN’ of object

Uncaught TypeError: Cannot assign to read only property ‘undefined’ of object

In the console there error will look like the below-

Restriction #4: Prevent “this” to refer to the global(window) object

Check the following code without strict mode-

function bigBoxFunc() {
  console.log(this);
}

bigBoxFunc(); // logs window object

Here we have declared the function “bigBoxFunc” in the global context and then invoked it. Inside the function “this” refers to the global “window” object and logs output like below-

Window {0: Window, window: Window, self: Window, document: document, name: '', location: Location, …}

But if we use strict mode here, then inside the function “this” will have the value “undefined“.

"use strict";

function bigBoxFunc() {
  console.log(this);
}

bigBoxFunc(); // logs undefined

Output-

undefined

This is such an important case and we need to be conscious while using “this” in strict mode.
Check details of the behavior of “this” in JavaScript here- “this” in JavaScript

Restriction #5: Prevent delete

Using “delete” can be problematic and introduce issues/bugs that are difficult to debug.

In strict mode, the usage of delete is restricted in the script and throws SyntaxError. Check code below

"use strict";

var bigVal = 1;

delete bigVal; // This line throws error because of delete


function bigBoxFun() {
    console.log("bigboxcode func");
}

delete bigBoxFun;  // This line also throws error because of using delete

Usage of delete in strict mode throws an error with the message-

Uncaught SyntaxError: Delete of an unqualified identifier in strict mode.

The error message looks like the image below in the browser console-

Restriction #6: Prevent duplication of function param

In the non-strict mode if we declare and use the same parameter name for the same function multiple times, then the code does not complain. It will be executed. Check the following code-

function bigBoxFun(param1, param2, param3, param1) { // "param1" is used multiple times
    console.log(param1, param2, param3);
    // logs "40 20 30"
}

bigBoxFun(10, 20, 30, 40);

The param “param1” parameter takes the value that is assigned to the later one. So “40” is the value of “param1” in the function.

This causes confusion. Ideally we should not be able to use the same parameter name multiple times. Strict mode helps us to prevent the param name duplication-

"use strict";

function bigBoxFun(param1, param2, param3, param1) { // Causes SyntaxError for duplicate parameter
    console.log(param1, param2, param3);
}

bigBoxFun(10, 20, 30, 40);

In strict mode we will get the following error-

Uncaught SyntaxError: Duplicate parameter name not allowed in this context

In the console the message will like image below-

Enabling the strict mode inside the function, also triggers the same error-

function bigBoxFun(param1, param2, param3, param1) { // Causes SyntaxError for duplicate parameter
    "use strict";
    console.log(param1, param2, param3);
}

Restriction #7: “eval” related restriction

Check the code below-

var eval = 99;

console.log(eval);
// Logs "99" as result

This code logs “99”, when run in normal mode.

Strict mode prevents usage of the “eval” keyword as a variable name-

"use strict";

var eval = 99; // Error

We get an error message-

Uncaught SyntaxError: Unexpected eval or arguments in strict mode

In the console, it looks like image below-

Now, let’s take a look at the usage of “eval“.

eval” executes the code provided to it. But the variables and some declaration leaks out of it.

Say we redeclare a variable inside the “eval“, which will overwrite the variable, and in the later part of the script, we would face bugs, as it will be difficult to track where the change happened-

var bigVal = 99;

eval("var bigVal = 1000");

console.log(bigVal);
// logs 1000 as the value is changed inside the eval

In strict mode, the code executed inside “eval” stays inside the context of “eval” and will not impact the outside code. Check the example below-

"use strict";

var bigVal = 99;

eval("var bigVal = 1000");

console.log(bigVal);
// logs 99 as the code inside eval does not affect code outside eval

Also, we will get a variable undefined error if the variable is declared inside “eval”, as the outside context does not have that value-

"use strict";

eval("var bigVal = 1000");

console.log(bigVal); // causes error

We will see an error with the message-

Uncaught ReferenceError: variable is not defined

In the console, it looks as in the image below-

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.