JavaScript ‘Strict Mode’.

Alwaz Qazi
4 min readJun 23, 2021

Have you ever seen someone’s code and noticed ‘use strict’ written at the top or anywhere else?

and wondered what’s that? well then don’t get confused because this blog will clear your concepts regarding ‘use Strict’ in JavaScript.

It is actually a new feature in ES6 which is used to instruct the browser to use the Strict mode.

In a nutshell, it tells our browser to:

Stop executing the code you don't understand and start throwing errors :)”.

Let’s understand this concept with an example.

Without Strict mode.

Now, look at this snippet of code without ‘use strict’. It may look fine, it’s working as well without any errors ,but it has some problems that browser is not telling by throwing errors because browser itself is confused. So, it’ll just execute it and we’ll get the output.

Now, let me list out the problems this snippet of code has.

  1. Never ever call a function before declaring it.

As you can see in the above example, sum() function is called before declaration, although it does work because JavaScript supports hoisting, but it’s not considered a good practice.

Let’s fix it and this is how it looks right now but, it’s still not perfect.

2) Always declare variables before assigning values to them.

As you can see the variable add that is adding the two parameters is not declared anywhere. If we console.log this variable we’ll get an error because, browser itself is not aware whether its a variable or something else.

Error: add is not defined

Now, lets try declaring it then see what do we get on the console.

after declaring var=add

As you can see we got undefined as the result of first console.

output = undefined

Now as you can see after declaring the variable we get undefined, without declaring we’re getting the result so its all getting a bit confusing because browser itself is confused.

Now this is where “use Strict” comes to rescue. To avoid all the silly stuff browser been doing.

If we execute the same code but this time with ‘use strict’.

and Voila we the error.! we got the error in the first place so we can follow best practices while writing code.

Output after use Strict

To understand it further lets make some more mistakes in code and execute it without strict mode.

Now, look here, I’ve given same names to parameters (a,a) and add is not declared again. lets see what do we get in the output.

we got the result but how do we know what argument was considered for the output?

Now if we do the same thing in strict mode.

Output after use strict

see, browser throwed error right away so we can fix our code and avoid these bad practices.

This is why strict mode is a very important concept. So make sure to write ‘use strict’ at the top of your file to avoid any confusion.

Thanks for reading!

Follow me for more programing content. 😃

--

--