What does use strict do in JavaScript, and what is the reasoning behind it?
Update for ES6 modules
Inside native ECMAScript modules (with import
and export
statements) and ES6 classes, strict mode is always enabled and cannot be disabled.
Original answer
This article about Javascript Strict Mode might interest you: John Resig - ECMAScript 5 Strict Mode, JSON, and More
To quote some interesting parts:
Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions.
And:
Strict mode helps out in a couple ways:
- It catches some common coding bloopers, throwing exceptions.
- It prevents, or throws errors, when relatively "unsafe" actions are taken (such as gaining access to the global object).
- It disables features that are confusing or poorly thought out.
Also note you can apply "strict mode" to the whole file... Or you can use it only for a specific function (still quoting from John Resig's article):
// Non-strict code...
(function(){
"use strict";
// Define your library strictly...
})();
// Non-strict code...
Which might be helpful if you have to mix old and new code ;-)
So, I suppose it's a bit like the "use strict"
you can use in Perl (hence the name?): it helps you make fewer errors, by detecting more things that could lead to breakages.
Strict mode is now supported by all major browsers.
What does use strict do in JavaScript, and what is the reasoning behind it?
Update for ES6 modules
Inside native ECMAScript modules (with import
and export
statements) and ES6 classes, strict mode is always enabled and cannot be disabled.
Original answer
This article about Javascript Strict Mode might interest you: John Resig - ECMAScript 5 Strict Mode, JSON, and More
To quote some interesting parts:
Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions.
And:
Strict mode helps out in a couple ways:
- It catches some common coding bloopers, throwing exceptions.
- It prevents, or throws errors, when relatively "unsafe" actions are taken (such as gaining access to the global object).
- It disables features that are confusing or poorly thought out.
Also note you can apply "strict mode" to the whole file... Or you can use it only for a specific function (still quoting from John Resig's article):
// Non-strict code...
(function(){
"use strict";
// Define your library strictly...
})();
// Non-strict code...
Which might be helpful if you have to mix old and new code ;-)
So, I suppose it's a bit like the "use strict"
you can use in Perl (hence the name?): it helps you make fewer errors, by detecting more things that could lead to breakages.
Strict mode is now supported by all major browsers.
Why is use strict a plain string and not a JavaScript reserved keyword?
Yes, it's for backwards compatibility. Some sources:
https://blog.maisie.ink/js-strict-mode/
Strict mode had to be an opt-in feature to maintain backwards
compatibility with old scripts. Some old scripts relied on features
that strict mode deprecated, and thus, would need to run in non-strict
mode by default. Additionally, the opt-in syntax'use strict';
is just
a string literal, which allowed new scripts to run in old browsers.https://medium.com/jp-tech/introduction-to-strict-mode-in-javascript-fb977bab697c
[Why not change the ECMAScript specification completely instead of
introducing an extra "strict mode"?] Perhaps part of it is to ensure
that some backward compatibility between ES5 and the previous version
is ES3, partly so that ECMAScript retains simplicity and flexibility
from before, rather than being limited by the new rigid added ruleshttps://johnresig.com/blog/ecmascript-5-strict-mode-json-and-more/ (John Resig)
Note the syntax that’s used to enable strict mode (I love this!). It’s
simply a string in a single statement that happens to contain the
contents “use strict”. No new syntax is introduced in order to enable
strict mode. This is huge. This means that you can turn strict mode on
in your scripts – today – and it’ll have, at worst, no side effect in
old browsers.(found via this answer)
Even more authoritative:
an email by Waldemar Hartmann on the es5-discuss mailing list (apparently a precursor to es-dicuss?), found via those ancient meeting notes:
[…] the general concept of the use strict directive was that it generally
followed lexical rules of ECMAScript statements and might even appear
unquoted in future versions of the language that had opt-in of
syntactic extensions.the ES5 specification itself notes on the
The ExpressionStatement productions of a Directive Prologue are
evaluated normally during evaluation of the containing SourceElements
production. Implementations may define implementation specific
meanings for ExpressionStatement productions which are not a Use
Strict Directive and which occur in a Directive Prologue.so it's not only backwards-compatible but also forwards-compatible - and this was indeed used for the
"use asm";
directive laterthe official paper by the spec authors Allen Wirfs-Brock and Brendan Eich on JavaScript explains the reasoning in detail:
An early issue was how the opt-in to strict mode would work. […] One
possibility was to use a special form of comment as a directive.
However, the ES3.1 working group was reluctant to make comments, of
any form, semantically significant because JavaScript minimizers
remove comments. Allen Wirfs-Brock observed that the syntax of an
ECMAScript ExpressionStatement makes any expression, including those
that consist of only a literal string constant, into a valid statement
as long as it is explicitly or implicitly (via ASI) followed by a
semicolon. That means that a statement such as"use strict";
is
syntactically valid ES3 code. Because it is simply a constant value,
evaluating it has no side effects in ES3. It is a no-op. It appeared
quite safe to use such a statement as the opt-in for strict mode as it
seemed highly unlikely that any existing JavaScript code would already
have used that exact statement form and an ES3 implementation would
ignore its presence in any ES5 code that was loaded. The working group
adopted that idea. A statement of the form"use strict";
occurring
as the first statement of a script or a function body indicated that
the entire script or function should be processed using strict mode
semantics.
nodejs need use 'strict use'?or what is the best practice of node's strict mode?
Use it always. If nothing else, it ensures that your code is properly written, and cross browser compatible as it can be. It also will reveal mundane syntax errors that would otherwise go unfound, and lead to hours of unnecessary debugging.
Benefits of Use Strict in JS
There are a zillion benefits to strict mode, but since you asked specifically about performance, not just the good coding benefits, here's what MDN says about that:
Strict mode makes several changes to normal JavaScript semantics.
First, strict mode eliminates some JavaScript silent errors by
changing them to throw errors. Second, strict mode fixes mistakes that
make it difficult for JavaScript engines to perform optimizations:
strict mode code can sometimes be made to run faster than identical
code that's not strict mode. Third, strict mode prohibits some syntax
likely to be defined in future versions of ECMAScript.
So as you asked, according to the Firefox folks at MDN, strict mode code can sometimes run faster.
For general benefits of strict mode, see What does "use strict" do in JavaScript, and what is the reasoning behind it?
When to NOT use strict mode in javascript?
So, when is a good choice to not use strict mode?
Strict mode will throw reference error when found non declared variables and in some cases.
If you have such an unrestrictedly typed code, that is used variables without declaring. One variable declared within some function/scope and used from somewhere else(it will be undeclared there) and you can't rewrite/change them, then you should not go for "use strict;"
mode because it will break the code.
From MDN
Strict mode makes several changes to normal JavaScript semantics.
- strict mode eliminates some JavaScript silent errors by changing them to throw errors.
- strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be
made to run faster than identical code that's not strict mode.- strict mode prohibits some syntax likely to be defined in future versions of ECMAScript.
When in strict mode
You can't just use variables without declaring them as you do in non strict mode
That is
The following will work because it is non strict mode
a = "Hello World";
console.log(a);
The following won't work because it is in strict mode
'use strict';
a = "Hello World"; // => Throw a reference error
console.log(a);
The above code will throw a reference error because variable a
is used without declaring it.
So, you should use
'use strict';
var a = "Hello World";
console.log(a);
Example in non strict mode
a = "Hello World";
console.log(a);
Can we write use strict at the top of our JS file and It would validate all functions and statements?
You only need to add it once at the top of the file.
See this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
Strict mode applies to entire scripts or to individual functions.
To invoke strict mode for an entire script, put the exact statement "use strict"; (or 'use strict';) before any other statements.
// Whole-script strict mode syntax
'use strict';
var v = "Hi! I'm a strict mode script!";
Why is use strict still a string literal?
Compatibility across all browsers and JS runtime engines.
E.g., http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
No new syntax is introduced in order to enable strict mode. This is huge. This means that you can turn strict mode on in your scripts – today – and it’ll have, at worst, no side effect in old browsers.
Related Topics
How to Use a Variable in a Regular Expression
Use Dynamic Variable Names in JavaScript
Window.Onload VS $(Document).Ready()
JavaScript Equivalent to Printf/String.Format
Detect When a Browser Receives a File Download
How to Use Unicode-Aware Regular Expressions in JavaScript
Get the Highlighted/Selected Text
How to Work Around JavaScript'S Parseint Octal Behavior
How to Check If an Element Is Hidden in Jquery
Can Scrapy Be Used to Scrape Dynamic Content from Websites That Are Using Ajax
What Is the !! (Not Not) Operator in JavaScript
$(Document).Ready Equivalent Without Jquery
What Characters Are Valid For JavaScript Variable Names
Accessing the Web Page'S Http Headers in JavaScript