Becoming strict in JS 🤨

JSwL: Episode 5

·

2 min read

For a long time, JavaScript has evolved without any compatibility issues. Why? New features were added without changing old functionality.

JS was designed to be simple, and for that reason, operations that should cause an error are forgiven. While this solves the immediate problem, it could create worse problems in the future.

This is where strict mode comes in; it treats these mistakes as errors so they can be fixed.

Two things to take note of:

  • Classes and modules make use of "use strict" by default.

  • Keywords reserved for future JavaScript versions can NOT be used as variable names in strict mode.

Here are 3 quotes

“Strict mode makes it easier to write "secure" JavaScript.

…JavaScript must be partially transformed before it is run, to censor access to forbidden functionality.” - MDN

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode

“It is not a statement, but a literal expression, ignored by earlier versions of JavaScript.

You can use strict mode in all your programs. It helps you to write cleaner code, like preventing you from using undeclared variables.“ - w3schools

https://www.w3schools.com/js/js_strict.asp

“Note in advance that "use strict" can be put at the beginning of a function. Doing that enables a strict mode in that function only. But usually, people use it for the whole script.

There is no directive like "no use strict" that reverts the engine to the old behavior.

Once we enter strict mode, there’s no going back.” - JS info

2 code samples

Take note of the difference, “y” is assigned but not declared.

// sample 1
x = 3.14;       // This will not cause an error.
myFunction();

function myFunction() {
  "use strict";
  y = 3.14;   // This will cause an error
}

1 exercise

// sample 2
"use strict";
myFunction();

function myFunction() {
  y = 3.14; // This will also cause an error because y is not declared
}

That's a wrap! see you on the next one.

Connect with me on Twitter.

Â