What is Strict Mode in JavaScript?
Tags: webdev, javascript, beginners, programming
Published: 2023-09-21 19:37:21

Strict mode is a JavaScript feature that makes the interpreter more strict with JavaScript syntax reducing the likelihood of mistakes in your code. If you are not using a strict mode then you are in a sloppy mode.

In this post, we are going to cover the basics of strict mode and cover the most important features of it. Here and there, I might recommend some additional readings to ease your understanding of strict mode. 

## Creating Strict Mode
In order to enable a strict mode in your script, you simply need to add “use strict” at the very first line of your script.

![Creating Strict Mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/551zldo98qatd3w9r5da.png)


On the other hand, strict mode and sloppy mode can coexist. You can use both in the same file.

To use both strict and sloppy modes, you need to write the code that you want in strict mode after the “use strict” while the rest before the “use strict”.

![Creating Strict Mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/arg3cplhpnb9jf9uzkkk.png)



Additionally, you can use strict mode inside the function body which is often mentioned as function-level strict mode.

![function-level strict mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fduwdl78waobbii20omg.png)

On the other hand, you cannot use strict mode inside the function if it is using default parameters, rest, or restructuring.

**Default parameters example**

![Default parameters example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1dfk65pa67vs42cxgjkk.png)



**Rest parameters example**

![Rest parameters example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/26l6ul9arps3o4cqov5n.png)



**Destructured parameters example**

![Destructured parameters example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lvcrcg6e3jxapjekzqv9.png)



## Automatic strict mode
There are various situations when strict mode is enabled automatically and you don’t need to enable it yourself.

**Strict mode is automatically applied in:**

### Classes
In all parts of the class, strict mode is enabled automatically.

![Automatic strict mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/py1l09ip7wcxbvjo6wpr.png)



### Modules
When using ES6 JavaScript modules, the entire module works in strict mode. Modules are reusable functions that can encapsulate code and separate some functionalities.

![Automatic strict mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rzvkd45rpwa1mvd6j4ff.png)



### JSON (JavaScript Object Notation)
JSON is a data format often used to transmit data between servers and web applications. It always works in a strict mode and you cannot turn it off.

![Automatic strict mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gkeyvfvg9mmytevx1opt.png)



## What exactly does Strict Mode do?
When struct mode is enabled, the syntax of JavaScript changes and so does the runtime. Let’s cover every change that takes place when going from sloppy mode to strict mode.

### Undeclared variables
In strict mode, you cannot re-declare a variable without using var, let, or const. This feature prevents us from creating global variables.

_If you are not familiar with variables, I recommend you read my post about [variables](https://dev.to/catherineisonline/variable-declarations-in-javascript-1915)._

![Undeclared variables](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4d0wj8e9dske0yltaw2b.png)



### Object property assignment
There are 3 situations where you cannot assign property in strict mode.

#### Non-writable property
In Objects, properties have their attributes, one of which is writable. Writable defines whether the value can be changed.

![Non-writable property](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fq8v5wp62ga5q6ww6eb7.png)



When in a sloppy mode, if you try to assign a new value even if the writable is false, it’s not going to throw any error. It will not rewrite the value but the error will remain “silent”.

![Non-writable property](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/apt67if4a2mxbyoc3b1b.png)



In the strict mode, however, you are going to receive an error and won’t reach the console.log line.

![Non-writable property](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/645zdiswmpg21epd434g.png)

![Non-writable property](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8vl4lzxpsqin6q6nseoo.png)



#### Getter-only property 
In objects, we have a special method that starts with a getter which retrieves a property value, and also a setter method that sets/modifies a property. 

A getter-only property means that it provides only a way to get the value. Getter-only properties automatically become read-only. 

Read-only means that the object property attribute writable is set to false - it cannot be modified.
In a sloppy mode, we will have a similar situation to the above example. There will be no errors thrown.

![Getter-only property](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wbm2pdtn7qeon6xcfcl5.png)



While in the strict mode, we will receive an error.

![Getter-only property](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1cmb5gzbcy6im0ah9ppj.png)



#### Non-extensible object
In JavaScript, we can make objects non-extensible which means they won’t be able to receive any new properties.

![Non-extensible object](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8p4lvku520eoobrdoqwj.png)



In this example, we aren’t going to receive any errors. But let’s enable strict mode.

![Non-extensible object](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ydbplpnnd1exsfybkzk0.png)


![Non-extensible object](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0kxvbu7n9upp0zf57067.png)



And that is when we receive an error.

### Object property deletion
Object properties that have an attribute configurable set to false, cannot be deleted. This attribute controls whether an attribute can be deleted. Similar to the examples above, if we try to delete an unconfigurable attribute, it will not delete it but will not throw an error either!

![Object property deletion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3nfnwyug6j52qubi2hx7.png)

In strict mode, however, we will see an error:

![Object property deletion](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/koz0cbln1f6s51msg90e.png)



### Duplicate parameters
In sloppy mode, if we repeat the parameter names, we will not see any error again!

![Duplicate parameters](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3i13tdiiqvkf568zsa5s.png)


It might seem so easy but when you have many parameters or more complex code, you might miss this error.

![Duplicate parameters](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0c2oz1xd2knnh5ts90kw.png)



### Leaking eval
Eval in JavaScript is a function that can execute a code written as a string. So if I write a function in a string, I can actually execute it even if it’s a string.
If we use it in a sloppy mode we will be able to declare a variable with var in string.

![Leaking eval](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0j31b8kxo191s9tbkfy8.png)


In a strict mode, however, it’s not allowed:

![Leaking eval](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eqwltnjqzdswjynde3u8.png)



### Eval and arguments assignment/binding
Besides restricted usage of eval strings, we also cannot assign any value to eval as well as arguments object.
Without a strict mode, it will work perfectly:

![Eval and arguments assignment/binding](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e0r3pgmlnzbvhoezwx2b.png)

In a strict mode, it will not reach the console.log:

![Eval and arguments assignment/binding](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gkqxantkjixa047hl0w0.png)



_If you are not sure what arguments are, I recommend you to read about the arguments object section in a post about [objects](https://dev.to/catherineisonline/the-complete-guide-to-javascript-functions-304g)._

### Properties on primitive values
In JavaScript, you cannot add properties to primitive values.
Primitive values are data types that represent one value — undefined, null, boolean, string, number, and symbol.
If you try to do so anyway, in a sloppy mode it won’t warn you about anything.

![Properties on primitive values](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vq5n09o0307vfhufdb2n.png)

Once we enable strict mode, we will see the error:

![Properties on primitive values](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/os0h2pkl7ru58h68isvo.png)

![Properties on primitive values](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f1y66c0exoq24128pczb.png)


### Parameter and argument indices synchronization
Before going further, make sure you get familiar parameters and arguments in my post about [functions](https://dev.to/catherineisonline/the-complete-guide-to-javascript-functions-304g).

When we don’t use a strict mode, parameters and arguments can lose synchronization and act unexpectedly.
Let’s inspect the example below where we use a sloppy mode:

![Parameter and argument indices synchronization](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h04wued30en9vmz9nvho.png)



Take a closer look at each console and guess why we have such results from your own experience.

We have a parameter “a” where we passed an argument 1. In the function body, we try to reassign a value to a parameter with a value of 12. 

Next, we also assign a value with the help of arguments object by targeting the value with the index.

In other words, in both cases, we tried to change the value of the “a” parameter — first via the parameter name and then via the arguments object and index. As a result, we get the value 13 everywhere as it was the last value we assigned.

Now look at what happens in the strict mode!

![Parameter and argument indices synchronization](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z88h9rsczk3gry4ihq59.png)


What is going on here? We try to do the same but we have some weird results. The attempt to reassign the value to the “a” parameter failed. 

Why?

Because in a strict mode, the arguments object and parameter do not sync and because variable assignment works differently in this case. 

What happened is that the “a” we wrote inside the function body [shadowed](https://dev.to/catherineisonline/what-is-variable-shadowing-in-javascript-59ci) the parameter and now is acting like a separate variable not connected to the parameter. 

But the argument object acts as expected and plays the main role now of controlling the parameter value.

### This keyword
The this keyword in JavaScript refers to various scopes depending on where and how it’s used. When we use it globally, outside any functions, object, or block, this refers to the global object (window).

![This keyword](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vxzpy48ihosn079e4eih.png)


![This keyword](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/db4nkp99pvbt7oq86igq.png)


However, when we use a strict mode it becomes undefined which helps to avoid extra errors in later usage of this keyword.

![This keyword](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8kfmainmobsr52z6hqgk.png)



### Stack-walking properties
Functions in JavaScript have a property called caller. It returns a reference to the function that we call the target function. Here is an example:

![Stack-walking properties](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zn7z7f8t9ui12q5ti9wy.png)



It will return a function reference from where the function was called, in our case, we called the function from the callerFunc:

![Stack-walking properties](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fk1wrtw80ieqv999hdy6.png)


However, in a strict mode, it’s not possible as such access to the caller might cause vulnerability issues.
Here is what happens in a strict mode:

![Stack-walking properties](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z3swp04s1uzl45tpr7bm.png)

![Stack-walking properties](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y21xnr2hyp49wxn6gwaa.png)



We also have another property called callee. This property used to be useful for recursive functions when a function needed to access/refer to itself. A recursive function is a function that calls itself until meets specific criteria.
Here is an example of a recursive function with a callee property that calls itself until it reaches one and returns the sum of each number from 1 to the number we passed to it:

![Stack-walking properties](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4whctu5jdlu8zjgj7j5v.png)



We can no longer do this in a strict mode:

![Stack-walking properties](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gwrhq46amn7h5okt3ije.png)


### More reserved words
On top of everything, strict mode enables even more reserved words in JavaScript. Reserved words in JavaScript are the words that already have some usage in JavaScript syntax so you cannot name anything with these words, they are already in use.

For example, you cannot create variables with names like const, try, this, true, and so on. 

**Strict mode adds even more reserved words:**
* interface
* implements
* let
* package
* private
* protected
* public
* static
* yield


## Pros and cons of a strict mode
Do we really need a strict mode or it’s an extra layer of complexity?

I believe that these days everyone should be using a strict mode. Even if you are a senior and have years of experience, we all are human and might make mistakes. A strict mode is a helping hand in avoiding some errors. Its features help to identify issues at the very start of the project instead of piling up many problems at the later stage.

On the other hand, if you have a complex project built with older JavaScript and you decide to enable strict mode, it might take some time to switch and update the code. The existing codebase might not be suitable for the strict mode and it will make things even harder. But it’s a modern world and I think everyone should start adapting to new things.

##Conclusion
In conclusion, a strict mode in JavaScript is a powerful feature that improves the language and makes it more reliable at the very start.

It prevents unintentional global variable creation, doesn’t silence the errors, and shows us right away where we need to make corrections exactly. 

It also helps to control the this keyword and doesn’t refer it to the global object.

Even though it’s not very easy to adjust an old codebase when switching to a structure mode, it’s still a huge step toward cleaner and safer code.