Get started with 33% off your first certification using code: 33OFFNEW

Understanding JavaScript Strict Mode

4 min read
Published on 22nd May 2023

JavaScript is a versatile and widely-used programming language for web development. However, its flexibility can sometimes lead to unintended consequences, making it crucial for developers to write robust and maintainable code. One way to achieve this is by using JavaScript's "strict mode."

For a high-level intro to JavaScript's strict mode you can also consult the MDN docs.

In this article, we'll explore JavaScript strict mode in depth, discussing what it is, how it works, and how it can help you write better code. We'll also provide code examples to illustrate the benefits and nuances of strict mode. This comprehensive guide aims to give you a thorough understanding of strict mode and its importance in your JavaScript projects.

What is Strict Mode?

Strict mode is a feature introduced in ECMAScript 5 (ES5) that enables developers to opt-in to a more strict and safer variant of JavaScript. When activated, it enforces stricter rules and constraints, helping to catch common coding errors and improve code quality. Strict mode can be enabled on a per-file or per-function basis, allowing developers to choose where to apply its constraints.

We recently covered declare(strict_types=1) usage in PHP, which is a similar concept to JavaScript's strict mode but in PHP.

Why use Strict Mode?

  1. Error Prevention: Strict mode helps prevent potential bugs by throwing errors for problematic code that would otherwise be silently ignored or cause unexpected behavior.
  2. Easier Debugging: By catching errors early, strict mode can make debugging faster and more efficient.
  3. Improved Performance: Some optimizations are only possible in strict mode, as it eliminates certain error-prone language features.
  4. Future-Proofing: Strict mode disallows the use of some deprecated or soon-to-be-deprecated features, helping your code remain compatible with future versions of JavaScript.

How to enable Strict Mode

Enabling strict mode is done in your code. Simply add the following to the top of your JavaScript file:

"use strict";

This directive informs the JavaScript interpreter to enforce strict mode rules for the entire file or function in which it appears. Keep in mind that enabling strict mode in one script or function doesn't affect other scripts or functions.

Using strict mode in Node

Node also supports strict mode. You have 2 options with this approach, this first is to use `"use strict;" at the top of the files you're processing in Node.

The second is to load node via the cli in strict mode:

node --use_strict

The key thing to remember with this approach is that you're loading the entire application in strict mode. This will include any third-party libraries you are using, which may not play nicely in strict mode. There is an argument that says that if a third-party doesn't work well in strict mode then perhaps you shouldn't be using it, but that's for you to decide.

Strict Mode Constraints

Strict mode enforces several rules and constraints that help improve code quality. Here are some of the most significant changes:

Variable Declaration

In strict mode, you must declare variables with the var, let, or const keyword before using them. Otherwise, an error will be thrown. This helps prevent accidental global variable creation.

// Non-strict mode
undeclaredVariable = 42; // Creates a global variable

// Strict mode
"use strict";
undeclaredVariable = 42; // Throws a ReferenceError

Duplicate Parameter Names

Strict mode disallows functions with duplicate parameter names, throwing a syntax error.

// Non-strict mode
function duplicateParameters(a, a) { // No error
}

// Strict mode
"use strict";
function duplicateParameters(a, a) { // Throws a SyntaxError
}

Octal Literals

Octal literals (e.g., 0123) are not allowed in strict mode, and attempting to use them will result in a syntax error. Instead, use the 0o prefix for octal numbers.

// Non-strict mode
var octal = 0123; // No error

// Strict mode
"use strict";
var octal = 0123; // Throws a SyntaxError
var octal = 0o123; // Correct octal syntax in strict mode

Assigning to Read-Only Properties

In strict mode, attempting to assign a value to a read-only property (such as a global variable like undefined or a built-in object's read-only property) will result in a TypeError.

// Non-strict mode
undefined = 42; // No error

// Strict mode
"use strict";
undefined = 42; // Throws a TypeError

with Statement

The with statement is disallowed in strict mode, as it can lead to ambiguous and hard-to-debug code. Using with in strict mode will result in a syntax error.

// Non-strict mode
with (object) {
  // Do something with object's properties
}

// Strict mode
"use strict";
with (object) { // Throws a SyntaxError
}

eval Changes

In strict mode, eval has its own scope, and variables declared inside an eval call don't leak into the surrounding scope. Additionally, assigning to eval or using it as a function name is disallowed.

// Non-strict mode
eval("var localVar = 42;");
console.log(localVar); // Logs 42

// Strict mode
"use strict";
eval("var localVar = 42;");
console.log(localVar); // Throws a ReferenceError

this Value

In non-strict mode, the this value inside a function called without an explicit receiver (e.g., as a standalone function, not a method) defaults to the global object. In strict mode, this is undefined, helping prevent accidental modifications to the global object.

// Non-strict mode
function logThis() {
  console.log(this);
}
logThis(); // Logs the global object (e.g., `window` in browsers)

// Strict mode
"use strict";
function logThis() {
  console.log(this);
}
logThis(); // Logs `undefined`

JavaScript strict mode is a powerful tool that can help you write more robust, maintainable, and future-proof code. By enforcing stricter rules and constraints, strict mode helps you catch common coding errors, improve performance, and ensure compatibility with future versions of JavaScript. By understanding and embracing strict mode, you can elevate your JavaScript development skills and create better web applications.