strict
mode in JavaScript (JS) was added in the new ECMAScript version 5. strict
mode enables certain JS code to behave differently semantically in order to make it more secure. As such, browsers that do not support the use of strict
mode execute code written in strict
mode differently than the browsers that do.
To write JS code in strict
mode, use the code below.
'use strict';
strict
mode can be applied to the entire script or to individual functions and modules.
To apply the use of strict
mode to the entire script, simply add the code above at the beginning of the script file, before any other code is written.
'use strict';
// the rest of the code goes here
let first = "first variable";
For use in a single function, the line of code is added as the first statement in the function body.
function strictFunc() {
'use strict';
var x = 5;
console.log(x);
}
- Modules are in
strict
mode by default.strict
mode does not apply to code written between braces ({}
).
strict
modestrict
mode makes several changes to the way JS code generally behaves. It makes certain mistakes, which are otherwise ignored, throw errors instead. It also performs optimization by fixing mistakes to make code run faster and prevents the use of certain syntax. The details of these changes are provided below.
NaN
would throw an error.0604
), as well as Octal escape literals (e.g. \24
).eval
and argument
from being used as variable names.eval
function is not permitted to create a new variable in the scope of which it is called.with
keyword cannot be used, making its use a syntax error.this
keyword to reference the global document
object is not allowed in order to make the script more secure. Instead, it returns undefined
.implements
, interface
, let
, package
, private
, protected
, public
, static
, and yield
.The effect of using strict
mode for some of the cases above is presented in the code below.
'use strict';num1 = 23; // will throw an error since num1 is not declaredvar eval = 10 + 3; // Error since eval can not be used as a variable name.var undefined = 100; // raises an error since assigning a value to a non-writable variableconsole.log(this); // produces 'undefined'.var octal_num = 067; // gives invalid number error, cannot use octal literals preceding with a 0delete num1; // cannot delete a local variable in strict mode