DEV Community

Cover image for What is JavaScript Strict Mode?
John Palmgren
John Palmgren

Posted on

What is JavaScript Strict Mode?

What is Strict Mode?

Strict mode is a way to make JavaScript errors more obvious. It can make the code more optimized for performance and prevent some security vulnerabilities.

You can get away with a lot in JavaScript. The language is very forgiving and many errors or things that could lead to errors are ignored. This can make it an easy language to learn because you're is not bombarded with syntax errors. But it can cause problems further down the line.

Strict Mode is a way to make JavaScript throw errors when it sees these mistakes which makes it easier to debug code and write better code in the first place.

Invoking strict mode

To invoke strict mode, use the syntax "use strict"; or 'use strict';

Strict mode can apply to a whole script or individual functions. For scripts, write "use strict" at the top of the script. For functions, you would put "use strict" at the top of the function body.

function example() {
    "use strict"
    return "this is an example function"
}
Enter fullscreen mode Exit fullscreen mode

Modules and Functions in JavaScript are automatically in strict mode.

How it works

converting mistakes into errors

Regular or "sloppy mode" JavaScript will allow a number of mistakes to pass by without causing any error messages. As mentioned earlier, this can make debugging difficult if your code stops working as you intend it.

One of the things strict mode stops you from doing is assigning a variable without using the const let or var keywords. In regular JavaScript, this would create a variable in the global scope and would continue to work. However, it's not the behavior we want. It creates the risk that you could misspell a variable and accidentally create a new variable.

      let number = 10;

      //misspelled variable will create new global variable
      // where the desired behavior is to update number variable
      numbr = 20

      console.log(number) //10
Enter fullscreen mode Exit fullscreen mode
      "use strict"

      let number = 10;
      numbr = 20 // throws error

      console.log(number) //only error output shown
Enter fullscreen mode Exit fullscreen mode

Another mistake that won't show up in regular JavaScript is assigning a value to a non-writeable variable. An example of a non-writeable variable is NaN. A mistake like NaN = 10; will only throw an error in strict mode. Another example of this would be undefined = "string".

Strict mode Will also prevent you from setting properties on primitive values. A primitive value is data that is not an object and has no methods. There are 7 primitive data types:

  • string
  • number
  • bigint
  • boolean
  • undefined
  • symbol
  • null

Setting a property on a primitive would look like

      "use strict"
      true.string = "hi" // typeError
      "string".update = 10 // typeError
Enter fullscreen mode Exit fullscreen mode

Some other mistakes that strict mode will turn into errors:

  • Trying to delete an undeletable property
  • Having the same names in a parameter eg function myFunc(a, a, b) {...}
  • Prefixing numbers with a 0. Find out why here

Optimizing variable use in JavaScript

Strict mode prevents certain actions which can lead to the code being less optimized. The JavaScript compiler is often able to say in which location each variable is stored. The variable name is mapped to its definition. This creates more optimized code. However, there are properties in JavaScript that make this impossible. Strict mode prevents these.

with

Strict mode prevents the use of the with property. with makes the properties of an object available as local variables in the statement.

      const myObject = { 
        title: "don't make me think", 
        author: "Steve Krug" 
      };

      with (myObject) {
        console.log (`this book was written by ${author}`) 
        // This book was written by Steve Krug

      }
Enter fullscreen mode Exit fullscreen mode

Using with is not recommended because any variable inside the block might relate to a property of the object or a variable in the surrounding scope. Because this can only be evaluated at runtime it prevents the code from being optimized. For this reason, using with in strict mode will throw an error.

eval

Like with, eval makes optimizing javascript code difficult. eval is a function that takes a string and evaluates it as JavaScript code.

cont x = 5
eval("x + 5") // 10
Enter fullscreen mode Exit fullscreen mode

The problem with eval (apart from its security vulnerability) is that it can introduce a variable into the surrounding scope. This means that code inside the eval function can change or override variables outside the function. And because JavaScript cannot check this until runtime, it can cause inefficiency.

In strict mode, any variables created in eval only exist within that function.

    eval("x = 5")
    console.log(x) // 5
Enter fullscreen mode Exit fullscreen mode
    "use strict"
    eval("x = 5")
    console.log(x) // ReferenceError
Enter fullscreen mode Exit fullscreen mode

Simplifying eval and arguments

In Javascript eval and arguments behave in ways that you might not expect. Mozilla says of the two:

Strict mode makes arguments and eval less bizarrely magical. Both involve a considerable amount of magical behavior in normal code: eval to add or remove bindings and to change binding values, and arguments by its indexed properties aliasing named arguments.

By using strict mode, eval and arguments are treated more like normal keywords

Making JavaScript more secure

JavaScript can be manipulated in the browser so that a person's private information can be accessed. JavaScript can prevent this from happening by partially transforming the JavaScript before it is run. However, if the code is not written well, this can take a lot of resources at runtime. Strict mode forces you to write JavaScript that will be more secure.

Without strict mode, it could be possible to access the global object from a function. This can then be used to manipulate JavaScript in ways that present a security risk. This has to do with the this value that is passed to the function. Because strict mode prevents this from being forced into an object, and if unspecified it will be undefined, malicious actors will not be able to access the global or window object. Read more about this here

Another security vulnerability in functions that strict mode sets out to fix is in JavaScript extensions. Using the extension .caller when a function is being called, will reveal the function that called it, and .arguments shows its arguments. This can allow access to potentially unsecured arguments through "secure" functions. If anyone tries to access .caller or .arguments in strict mode code the result will be a TypeError

New Keywords

In strict mode, there are some extra reserved keywords. These are words that are likely to be used in future versions of JavaScript. Their inclusion acts to ease the transition into newer versions of JavaScript. Some of these are:

  • implements
  • interface
  • package
  • private
  • protected
  • public
  • static
  • yield

For extra information on strict mode and more technical explanation on what it does, you can see the Mozilla documentation

Top comments (0)