JavaScript Strict Mode Explained: Benefits, Limitations & How to Enable

Feat 15699 Png

Imagine spending hours writing JavaScript, only to discover that a tiny mistake has slipped by, hidden deep in the code. JavaScript, by default, often lets these errors pass silently, making it difficult to spot problems until they cause real trouble. This is where JavaScript strict mode comes in, shining a light on issues that would otherwise stay invisible and helping us avoid headaches down the road.

Key Takeaways

  • Strict mode helps us find mistakes in our code by making errors visible instead of letting them go unnoticed
  • We can enable strict mode by adding use strict at the very start of our script or function
  • Strict mode stops us from using variables that are not declared, which helps prevent accidental global variables and makes our code more reliable
  • Some actions are not allowed in strict mode, like using the with statement or changing read-only properties, which helps us avoid confusing or risky code
  • When we use strict mode, the value of this inside a function is undefined if we do not set it, so we do not accidentally change the global object
  • Strict mode can make our code run faster because it lets JavaScript engines optimize our code better
  • By following strict mode rules, we write code that is easier to understand, more secure, and less likely to have hidden bugs

Activating JavaScript Strict mode

For activating Strict mode, you can add ‘use strict’; or “use strict”; at the beginning of the script.

Syntax:

‘use strict’;

// or

"use strict";

This statement should be the first statement in the script excluding comments as JavaScript just ignore them.

If there is any other statement before ‘use strict’; or “use strict”; then string mode will not activate.

Adding ‘use strict’; or “use strict”; at the beginning of the script has a global scope which makes all the code in that script executed in string mode.

Example:

"use strict";
name = "John";

console.log(name);

Output:

name = "John";
     ^

ReferenceError: name is not defined
    at Object.<anonymous> (C:\Users\ag290\OneDrive\Desktop\journalDev-2023\january\strict mode\app.js:2:6)
    at Module._compile (internal/modules/cjs/loader.js:759:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:770:10)
    at Module.load (internal/modules/cjs/loader.js:628:32)
    at Function.Module._load (internal/modules/cjs/loader.js:555:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:826:10)
    at internal/main/run_main_module.js:17:11

Here, we have got an error as Strict Mode doesn’t allow using an undeclared variable.

Without Strict Mode:

name = "John";

console.log(name);

Output:

John

Activating JavaScript Strict Mode in Individual Functions

You can also enable string mode for a particular function by adding  ‘use strict’; or “use strict”; at the beginning of the function.

Syntax:

function functionName() {
    ‘use strict’;
    // function body
}

// or

function functionName() {
    "use strict";
    // function body
}

This statement should be the first statement of the function excluding comments.

Adding ‘use strict’; or “use strict”; at the beginning of a function has a local scope which means all the code in that script is executed usually and the code inside the function will only execute in strict mode.

Example:

function Name() {  // Function without strict mode
    name = "Rack"
    console.log("Name is: " + name) // No error here
}

function Age() {  // Function with strict mode
    "use strict";
    age = "22"
    console.log("Age is: " + age) // Error here
}

Name()
Age()

Output:

Name is: Rack
C:\Users\ag290\OneDrive\Desktop\journalDev-2023\january\strict mode\app.js:8
    age = "22"
        ^

ReferenceError: age is not defined
    at Age (C:\Users\ag290\OneDrive\Desktop\journalDev-2023\january\strict mode\app.js:8:9)
    at Object.<anonymous> (C:\Users\ag290\OneDrive\Desktop\journalDev-2023\january\strict mode\app.js:13:1)
    at Module._compile (internal/modules/cjs/loader.js:759:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:770:10)
    at Module.load (internal/modules/cjs/loader.js:628:32)
    at Function.Module._load (internal/modules/cjs/loader.js:555:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:826:10)
    at internal/main/run_main_module.js:17:11
PS C:\Users\ag290\OneDrive\Desktop\journalDev-2023\january\strict mode> 

Here, the first function doesn’t cause any error but the second function throws an error, since it executes the code in strict mode, and as we know in strict mode, a variable is not used if it is not declared.

Actions Not Allowed in Strict Mode

Some typical actions that are forbidden in strict mode are given below:

1. Undeclared objects or variables.

We have already seen that using a variable or an object without declaring it is not allowed in strict mode.

Example:

"use strict";
user = {
    name: 'John',
    age: 30,
    gender: 'male',
}

console.log(user.name) // John

Output:

Reference Error

2. Deleting an object, variable, or function.

Example:

"use strict";
let user = {
    name: 'John',
    age: 30,
    gender: 'male',
}

delete user; // Error here

Output:

Syntax Error

3. Duplicating a parameter name.

Example:

"use strict";
function hello(value, value){
    console.log(value + " " + value);
}

Output:

Syntax Error

4. Writing to a read-only property, get-only property & undeletable property is not allowed.

Example:

"use strict";
const user = {};
Object.defineProperty(user, "name", {value:0, writable:false});

user.name = "John";

Output:

Type Error

4. Octal numeric literals & Octal escape characters are not allowed.

Example:

"use strict";
let num = "\010";   // Error here

Output:

Syntax Error

5. ‘eval’ cannot be used as a variable.

Example:

"use strict";
let eval = "Hello World";

console.log(eval);

Output:

Syntax Error

6. ‘arguments’ cannot be used as a variable.

Example:

"use strict";
let arguments = "Hello World";

console.log(arguments);

Output:

Syntax Error

7. ‘with’ is not allowed.

Example:

"use strict";
with ([1, 2, 3]) {
    console.log(toString()); 
}

Output:

Syntax Error

8. Keywords such as implements, interface, static, package, private, protected, public, let and yield are prohibited in strict mode.

Example:

"use strict";
let public = "public"; 

Output:

Syntax Error

Common Pitfalls

Forgetting to Place use strict at the Top

A common mistake is not putting use strict as the very first statement in a script or function. If there is any code, even a variable declaration or a comment, before use strict, strict mode will not activate. For example, if we write a variable before the directive, strict mode will be ignored and errors will not be caught as expected. To avoid this, always place use strict at the very top, before any other statements or code.

Assuming Strict Mode Is Enabled Everywhere

Strict mode does not apply automatically to all JavaScript files. If we forget to add use strict in a script or function, JavaScript will run in normal mode, which may allow silent errors. However, when using JavaScript modules, strict mode is enabled by default. It is important to check if the code is in a module or a regular script and add use strict where needed to ensure consistent behavior across all files.

Example: In a regular script, missing use strict means accidental global variables can be created, which can cause bugs that are hard to find.

Using Reserved Words as Variable Names

Strict mode does not allow the use of certain reserved words, such as eval or arguments, as variable or function names. If we try to use these as identifiers, JavaScript will throw an error. To prevent this, always avoid naming variables or functions with reserved keywords.

Example: Writing let eval = 5 in strict mode will cause an error.

Solution: Choose variable names that are not reserved by JavaScript.

Unexpected this Value in Functions

In strict mode, the value of this inside a function that is called without an object is undefined, not the global object. This can cause unexpected results if we expect this to refer to the global object. For example, calling a function directly will set this to undefined in strict mode.

Example: In strict mode, function show() { alert(this); } show(); will alert undefined.

Solution: Always call functions with the correct context or use arrow functions if the context should be inherited.

Frequently Asked Questions

What is strict mode in JavaScript?

Strict mode is a feature in JavaScript that helps us write safer code by catching errors and preventing certain unsafe actions that JavaScript usually ignores.

How do we enable strict mode in JavaScript?

We can enable strict mode by adding ‘use strict’ as the first statement in a script or a function, before any other code.

What are the main benefits of using strict mode?

Strict mode helps us find hidden bugs, stops the use of undeclared variables, and makes our code more secure and easier to maintain.

Are there any limitations or disadvantages to strict mode?

Strict mode can break older code that relies on JavaScript’s loose behavior, and it is not supported in Internet Explorer 9 or earlier versions.

What actions are forbidden in strict mode?

In strict mode, we cannot use undeclared variables, delete variables or functions, use duplicate parameter names, or use octal numbers and escape characters.

Does strict mode apply to the whole script or just parts of it?

If we place ‘use strict’ at the top of a script, it affects the whole file, but if we put it inside a function, only that function and its inner functions use strict mode.

Is strict mode automatically enabled in modules and classes?

Yes, all code inside JavaScript modules and classes uses strict mode by default, so we do not need to add ‘use strict’ manually in these cases.

What happens if we put ‘use strict’ after other statements?

If ‘use strict’ is not the first statement, strict mode will not activate, and the code will run in normal mode.

Can we turn off strict mode once it is enabled?

No, once strict mode is enabled in a script or function, we cannot turn it off for that section of code.

What are some common errors that strict mode helps catch?

Strict mode helps us catch mistakes like using undeclared variables, assigning values to read-only properties, and using duplicate parameter names in functions.

Is it still necessary to use strict mode in modern JavaScript?

It is still good practice to use strict mode in regular scripts and older code, but in modules and classes, strict mode is already enabled automatically.

Which browsers support strict mode?

All modern browsers support strict mode except Internet Explorer 9 and earlier versions.

AI Dev Assistant Tips

Modern AI tools like GitHub Copilot and ChatGPT can make it much easier for us to understand and use JavaScript strict mode. These tools can help us spot mistakes, explain strict mode rules, and even suggest code improvements. With their help, we can write code that is more secure and reliable.

Copy-Paste-Ready AI Prompt

Explain how to enable strict mode in JavaScript and list the main errors that strict mode can help us catch. Give clear code examples for both enabling strict mode in a whole file and inside a function.

  • We can ask AI tools to review our code and point out where strict mode rules are not being followed. This helps us avoid silent errors and makes our code safer.
  • When we are not sure about a strict mode error, we can describe the error message to an AI assistant and get a simple explanation along with a solution.
  • We can use AI to generate code snippets that already follow strict mode rules, saving us time and effort.
  • It is helpful to ask the AI for examples that show the difference between strict mode and normal mode. This makes it easier for us to see why strict mode is important.
  • We should always double-check the AI’s suggestions by testing the code in our own environment, since strict mode can behave differently in some situations.

About the Author

Aditya Gupta is a Full Stack Developer with over 3 years of experience building scalable and maintainable web applications. He is passionate about writing clean code and helping other developers level up their skills in the modern JavaScript ecosystem.

Connect on LinkedIn: https://www.linkedin.com/in/dev-aditya-gupta/

My Mission: To demystify complex programming concepts and empower developers to build better software.

Review Your Cart
0
Add Coupon Code
Subtotal