Home ยป JavaScript Strict Mode: A Comprehensive Tutorial

JavaScript Strict Mode: A Comprehensive Tutorial

Strict mode in JavaScript is a way to opt into a restricted variant of JavaScript. It helps you write cleaner code by throwing more errors and preventing certain actions that might lead to bugs or unexpected behavior.

Strict mode is a feature that has been around since ECMAScript 5 (ES5) and can be enabled globally or within a specific function.

This tutorial will explain how to enable strict mode in JavaScript, outline its benefits, and demonstrate its effects with practical examples.

1. Enabling Strict Mode

Strict mode can be enabled by adding the directive “use strict”; at the beginning of a script or a function.

Example 1: Enabling Strict Mode Globally

"use strict";

x = 10; // ReferenceError: x is not defined
console.log(x);
Explanation: In strict mode, all variables must be declared with let, const, or var. The line x = 10; attempts to create a global variable without declaring it first, which throws a ReferenceError.
Example 2: Enabling Strict Mode in a Function
function myFunction() {
  "use strict";
  y = 20; // ReferenceError: y is not defined
  console.log(y);
}

myFunction();

Explanation: Here, strict mode is applied only within the myFunction() function. Outside of this function, JavaScript code is not in strict mode.

2. Key Features and Restrictions of Strict Mode

Strict mode changes JavaScript's behavior in several ways. Below are some of the most significant restrictions and how they can help improve code quality.

2.1 Preventing Undeclared Variables

In non-strict mode, assigning a value to an undeclared variable implicitly creates a global variable. Strict mode disallows this and throws a ReferenceError.

Example 3: Preventing Undeclared Variables

"use strict";

try {
  undeclaredVariable = 100; // Throws ReferenceError
} catch (error) {
  console.error(error.message); // Output: "undeclaredVariable is not defined"
}

Explanation: In strict mode, you must declare variables using let, const, or var. This helps catch accidental global variables, reducing bugs.

2.2 Preventing Deleting Variables, Functions, and Function Arguments

Strict mode disallows deleting variables, functions, or function arguments using the delete keyword.

Example 4: Preventing Deletion of Variables and Functions

"use strict";

let number = 10;
function myFunction() {
  return number;
}

try {
  delete number; // Throws a SyntaxError
} catch (error) {
  console.error(error.message); // Output: "Delete of an unqualified identifier in strict mode."
}

try {
  delete myFunction; // Throws a SyntaxError
} catch (error) {
  console.error(error.message); // Output: "Delete of an unqualified identifier in strict mode."
}

Explanation: In strict mode, the delete operator can only be used on object properties. Attempting to delete a variable, function, or function argument results in a SyntaxError.

2.3 Preventing Duplicate Parameter Names

In non-strict mode, JavaScript allows functions to have parameters with duplicate names, but strict mode throws a SyntaxError.

Example 5: Preventing Duplicate Parameter Names

"use strict";

try {
  function duplicateParameters(a, a) { // Throws a SyntaxError
    return a;
  }
} catch (error) {
  console.error(error.message); // Output: "Duplicate parameter name not allowed in this context"
}

Explanation: Duplicate parameter names can cause unexpected behavior and bugs. Strict mode prevents this by disallowing duplicate names in function definitions.

2.4 Preventing Octal Literals

Strict mode disallows octal numeric literals (numbers starting with 0) and throws a SyntaxError if they are used.

Example 6: Preventing Octal Literals

"use strict";

try {
  let num = 010; // Throws a SyntaxError
} catch (error) {
  console.error(error.message); // Output: "Octal literals are not allowed in strict mode."
}

Explanation: In strict mode, octal literals are not allowed to avoid confusion and potential bugs.

2.5 this in Functions

In non-strict mode, this in a function refers to the global object (window in browsers). In strict mode, this is undefined if the function is not called as a method of an object.

Example 7: this in Functions

"use strict";

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

showThis(); // Output: undefined (in strict mode)

Explanation: In strict mode, this is undefined in a regular function (not an object method). This behavior helps prevent unintended errors, such as modifying the global object.

2.6 Preventing Writing to Read-Only Properties

Strict mode throws an error when you attempt to write to read-only properties of an object.

Example 8: Preventing Writing to Read-Only Properties

"use strict";

const obj = {};
Object.defineProperty(obj, 'readOnlyProp', {
value: 42,
writable: false
});

try {
obj.readOnlyProp = 100; // Throws a TypeError
} catch (error) {
console.error(error.message); // Output: "Cannot assign to read only property 'readOnlyProp' of object '#<object width="300" height="150">'"
}

Explanation: Strict mode enforces property write restrictions, helping prevent accidental changes to immutable data.

2.7 Preventing with Statements

The with statement is forbidden in strict mode as it can create confusion and make code harder to debug.

Example 9: Preventing with Statements

"use strict";

try {
  with (Math) { // Throws a SyntaxError
    console.log(PI);
  }
} catch (error) {
  console.error(error.message); // Output: "Strict mode code may not include a with statement"
}

Explanation: Strict mode disallows the with statement because it can make the code less predictable and more challenging to optimize.

3. Strict Mode in Modules and Classes

Strict mode is automatically enabled inside JavaScript modules and classes, even if “use strict”; is not specified.

Example 10: Strict Mode in Modules and Classes

// Assuming this code is in a module (file.js)
function moduleFunction() {
  // Strict mode is enabled by default
  x = 100; // ReferenceError: x is not defined
}

class MyClass {
  constructor() {
    // Strict mode is enabled by default in classes
    this.x = 10;
  }

  setX(value) {
    this.x = value;
  }
}

Explanation: You don't need to specify “use strict”; in JavaScript modules and classes because they inherently use strict mode.

Conclusion

Strict mode in JavaScript is a way to enforce cleaner, safer coding practices by restricting certain behaviors and throwing more errors.

It prevents common mistakes like creating global variables, using duplicate parameter names, writing to read-only properties, and more.

By using strict mode, you can write more robust and maintainable code, reducing the likelihood of bugs.

To use strict mode effectively:Add “use strict”; at the beginning of your script or function.Be mindful of the restrictions it enforces and adjust your coding habits accordingly.

Experiment with the examples provided to get a clear understanding of how strict mode affects JavaScript code!

You may also like