DEV Community

Cover image for Understanding 'Use strict' in JavaScript
Muslimat Mojeed
Muslimat Mojeed

Posted on

Understanding 'Use strict' in JavaScript

Introduction to strict mode in JavaScript

Having written some lines of JavaScript code, you are probably familiar with the quirks and challenges of the language. Perhaps you've encountered those undeclared variables that cause silent errors in your code, leaving you puzzled about their origins.
In the dynamic realm of JavaScript, where creativity meets complexity, developers often encounter subtle bugs and unexpected behaviors. To address these challenges, ECMAScript 5 (ES5) introduced a feature known as 'use strict'. The 'use strict' perform additional checks and apply stricter rules to code, helping to catch programming errors and potentially improving performance. It was a significant update to the language and has been widely adopted by developers due to its benefits in catching errors and improving code quality.
Whether you're just starting out or have some experience in JavaScript, this article will explore the fundamentals of strict mode in JavaScript. The significance and why every developer should know how to use it effectively will also be discussed.

What is Strict Mode?

Strict mode is a special mode in JavaScript that allows developers to opt into a set of rules and restrictions that are not enforced by default.
Strict mode in JavaScript is like having a helpful friend who keeps an eye out for mistakes while you're coding. It's a special set of rules that make JavaScript more careful about how it reads and runs your code.
It helps catch errors that would otherwise go unnoticed, such as using variables without declaring them first or defining functions with duplicate parameter names. By enabling strict mode, developers can write code that is safer, easier to maintain, and more compatible with future versions of JavaScript.

Why Use Strict Mode in JavaScript

  • It assists in writing safer and more readable code.
  • Strict Mode helps catch common programming errors which can lead to a more predictable and reliable code.
  • Strict mode helps developers write code that is more compatible with future versions of JavaScript, as it encourages the use of modern language features and best practices.
  • Strict mode prohibits some syntax that could be misleading or problematic.
  • Due to modifications that facilitate JavaScript engines' optimisations, code in strict mode occasionally runs quicker than identical code that isn't in strict mode.

Enabling Strict Mode in JavaScript

To enable strict mode in JavaScript, simply add the following line of code to the beginning of your script or function:

'use strict';
Enter fullscreen mode Exit fullscreen mode

This statement tells the JavaScript engine to enter strict mode for the current script or function, enabling the stricter rules and checks provided by strict mode.

Common errors and issues addressed by strict mode

The following are examples of some of the errors caught by strict mode:

  • Undeclared variables: In strict mode, trying to assign a value to a variable that has not been declared with var, let, or const will throw a ReferenceError. This helps catch potential issues with typos or variables that were intended to be declared but were missed.
   'use strict';
   x = 10; // ReferenceError: x is not defined
Enter fullscreen mode Exit fullscreen mode
  • Function parameter name restrictions: In strict mode, defining a function with duplicate parameter names (e.g., function func(a, a)) will throw a SyntaxError. This helps enforce unique parameter names, which can prevent confusion and bugs.
   'use strict';
   function func(a, a) { // SyntaxError: Duplicate parameter name not allowed in this context
       return a + a;
   }
Enter fullscreen mode Exit fullscreen mode
  • Duplicate property names: In strict mode, defining multiple properties with the same name in an object literal or function parameter list will throw a SyntaxError. This helps prevent accidental duplication of property names, which can lead to unexpected behavior.
   'use strict';
   var obj = {
       prop: 1,
       prop: 2 // SyntaxError: Duplicate data property in object literal not allowed in strict mode
   };
Enter fullscreen mode Exit fullscreen mode
  • Using eval in a local scope: When you use eval in a specific part of your code (like inside a function) and you're in strict mode, it creates a sort of "bubble" where any new variables you create inside that eval don't affect the rest of your code. This can be confusing because changes you make inside eval don't carry over to the main part of your code.
   'use strict';
   var x = 10;
   function evalInLocalScope() {
       eval('var x = 20;');
       return x; // Returns 10 because eval creates its own scope in strict mode
   }
Enter fullscreen mode Exit fullscreen mode
  • Octal syntax: In strict mode, octal literals (numbers with a leading zero, e.g., 012) are not allowed and will throw a SyntaxError. This helps prevent potential confusion with decimal numbers and improves code clarity.
   'use strict';
   var num = 012; //SyntaxError.
Enter fullscreen mode Exit fullscreen mode
  • Delete of an undeletable property: Trying to delete a property that is not deletable (such as properties of built-in objects like Object.prototype ) will throw a TypeError in strict mode. This prevents unintended deletion of critical properties.
   'use strict';
   delete Object.prototype; // TypeError: Cannot delete property 'prototype' of function Object() { [native code] }
Enter fullscreen mode Exit fullscreen mode

These examples illustrate some of the ways strict mode in JavaScript helps catch common errors and enforce stricter rules, ultimately leading to more reliable and maintainable code.

Best practices for using strict mode in JavaScript

Just like any other tool, it's important to use strict mode judiciously and understand its implications. In this section, we'll discuss best practices for using strict mode effectively:

When to Use Strict Mode

  • Use Strict Mode Globally: It's a good practice to enable strict mode at the beginning of your scripts or modules to ensure that the entire codebase benefits from its advantages. This can be done by adding 'use strict'; at the beginning of your JavaScript file or function.
//  strict mode syntax at the beginning of the script 
"use strict";
const myScript = "Yo! I just got activated!";
Enter fullscreen mode Exit fullscreen mode
  • Use Strict Mode in Functions: If you prefer to use strict mode only in specific functions, you can enable it at the beginning of those functions. This allows you to apply strict mode selectively, where it's most beneficial.
function myFunctionScript() {
  // Function strict mode 
  "use strict";
  function mySF() {
    return "Yo, I just got activated!";
  }
Enter fullscreen mode Exit fullscreen mode
  • Use Strict Mode in Modules: When working with JavaScript modules (ES6 modules), enabling strict mode at the beginning of each module is a recommended practice. This helps maintain a consistent and predictable coding environment within each module.

Potential pitfalls to avoid

While strict mode offers many benefits, there are some potential pitfalls to be aware of:

  • Compatibility issues: Not all browsers support strict mode, so using it may cause compatibility problems with older browsers. It's important to test your code in different environments to ensure compatibility.

  • 'use strict' is contagious: Once you enable strict mode in a script, all code within that script, as well as any other scripts included on the page, will run in strict mode. This can be problematic if other scripts are not intended to run in strict mode.

  • All or nothing: Once you enable it, it applies to all code within that scope. This means that if you only want to use strict mode for certain parts of your code, you'll need to separate those parts into different scripts or functions.

  • Performance impact: While enabling strict mode itself does not significantly impact performance, the additional error checking and restrictions imposed by strict mode can sometimes lead to slightly slower code execution. However, the benefits of catching errors early and writing more maintainable code often outweigh this minor performance impact.

It's important to weigh the benefits of strict mode against these potential pitfalls and use it judiciously in your projects. By understanding these details, you can leverage strict mode effectively to improve the quality and reliability of your JavaScript code.

Final thoughts

Conclusively, strict mode is a valuable tool that should be embraced by JavaScript developers. By enabling strict mode in your projects, you can write code that is more robust, reliable, and future-proof. So, the next time you start a new project or refactor an existing one, add 'use strict'; to the beginning of your scripts or functions and experience the benefits for yourself. It's a small step that can lead to significant improvements in your codebase.
This article has explored the fundamentals of using strict mode, it's significance and why it is essential for every JavaScript developer.

I hope a lot was gained from this article. Be free to drop your suggestions or questions in the comment box.

Further Reading

Explore these resources to deepen your understanding of strict mode.
MDN Web Docs on strict mode

Top comments (3)

Collapse
 
barry1003 profile image
Barry1003

This was very helpful and I learned a lot from you article

Thanks so much

Collapse
 
ockley profile image
Karsten Vestergaard

If there can be a small performance drop, could you maybe just comment it out for production?

I know it is a small thing, but for micro-optimization nerds?

Collapse
 
symplymuslimah12 profile image
Muslimat Mojeed

I don't think commenting it out is an option. The impact of 'use strict' on performance in minimal and it can unlikely have a significant effect on the overall performance of your application. Considerations should always be given to the benefits of using 'use strict' in code as this outweighs any performance impact.
So you can just leave it during development and during production too.