What is javascript "Use strict"

May 10, 2020

#Javascript

I’m pretty sure that you have already found this two words at the top of some javascript files, maybe you have ignored that , but let’s understand what is its purpose.

If we take a look to the official documentation we can notice that “It is a way to opt in to a restricted variant of Javascript”.
“Strict” doesn’t mean that we can use less JS functionality. The real aim is to highlight the silent errors by throwing errors.

Example

Variable declaration:

function foo() {
    answer = 42;   // The variable answer is not declared
}
foo(); // This call will not cause an error

function fooSafe() {
    "use strict";
    answer = 42;   // The variable answer is not declared
}
fooSafe(); // This call will raise "Uncaught ReferenceError: answer is not defined"

I know this example is really simple, but it could happen ( trust me, it will happen ) to forget to declare a variable and using the “Use Strict” mode will keep our code safe. It is also really important to use this mode because debugging will be much easier.

OMG! I’ve found a lot of projects where “Use Strict” is missing !

Wait wait.. let’s clarify 😁 Check the javascript version !
This functionality was provided with ES5 and you should manually add it while ES6 modules are always in strict mode by default.

Summary

“Use Strict” should be used in every ES5 projects because:

  • It prevents to run in silent error, so our code it will be stronger
  • It prevents syntax errors
  • It is already integrated in ES6 modules, so it will be the standard way to write js code.
  • It will help developers to easily find common mistakes

For further details check the official documentation.

Pingu 🐧


Written by Pingu who lives and works in Genoa building useful modern applications.

Something to share ?