JavaScript “use strict”
"use strict";
defines that JavaScript code should be executed in "strict mode".
For a long time, JavaScript evolved without compatibility issues. New features were added to the language while old functionality didn’t change. That had the benefit of never breaking the existing code. But the downside was that any mistake or an imperfect decision made by JavaScript’s creators got stuck in the language forever.
How to declare
- Ensure that “use strict” is at the top
- There’s no way to cancel
use strict
Some examples while implementing:
In the above example, declared inside a function, it has a local scope (only the code inside the function is in strict mode).
In the above example, we can see that using a variable, without declaring it, is not allowed.
Modern JavaScript supports “classes” and “modules” — advanced language structures (we’ll surely get to them), that enable use strict
automatically. So we don’t need to add the "use strict"
directive if we use them.
So, for now "use strict";
is a welcome guest at the top of your scripts. Later, when your code is all in classes and modules, you may omit it.
Also, this
keyword in functions behaves differently in strict mode. this
keyword refers to the object that called the function. If the object is not specified, functions in strict mode will return undefined
and functions in normal mode will return the global object (window).