Strict Mode
Strict mode in JavaScript is a way to opt into a stricter language version, enforcing rules that can help prevent common coding mistakes. It makes the code more predictable and easier to debug by restricting certain behaviours that could lead to errors or unexpected behaviour in non-strict mode.
Syntax
Strict mode can be enabled for an entire file by adding "use strict"
at the very beginning of the script as follows:
"use strict";
// All code here runs in strict mode
Strict mode can also be enabled within a specific function, which will only affect the code inside that function:
function example() {
"use strict";
// Only this function's code runs in strict mode
}
Example
The example below shows how strict mode prevents creating global variables accidentally. Without strict mode, assigning a value to an undeclared variable would automatically create a global variable:
x = 10;console.log(x);// 10
This gives an output as follows:
10
In strict mode, this results in an error, helping prevent unintended global variables:
'use strict';x = 10;// Throws an error: 'x is not defined'
The output for this code will be:
ReferenceError: x is not defined
Codebyte Example
The following example showcases that in strict mode, duplicate parameter names are not allowed:
This will throw a SyntaxError before the function is executed, with the message SyntaxError: Duplicate parameter name not allowed in this context
.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours