How to Use Strict Mode in JavaScript: Syntax and Examples
Use
'use strict'; at the top of a JavaScript file or function to enable strict mode, which helps catch common coding mistakes and unsafe actions. Strict mode changes how JavaScript runs by enforcing stricter parsing and error handling.Syntax
Strict mode is enabled by placing the exact string 'use strict'; at the beginning of a script or a function. This tells JavaScript to run in a stricter way, preventing some silent errors and unsafe actions.
- Global strict mode: Put
'use strict';at the very top of your JavaScript file. - Function strict mode: Put
'use strict';at the start of a function body to apply strict mode only inside that function.
javascript
'use strict'; function example() { 'use strict'; // function code here }
Example
This example shows how strict mode catches an error when you try to use a variable without declaring it first. Without strict mode, this would create a global variable silently.
javascript
'use strict'; function test() { x = 10; // Error: x is not defined in strict mode } try { test(); } catch (e) { console.log(e.message); }
Output
x is not defined
Common Pitfalls
Some common mistakes when using strict mode include:
- Forgetting to put
'use strict';as the very first statement in a script or function. - Using reserved keywords as variable names, which strict mode disallows.
- Assigning values to read-only properties or non-writable variables.
Here is an example showing a wrong and right way to declare variables in strict mode:
javascript
'use strict'; // Wrong: undeclared variable // x = 5; // Throws ReferenceError // Right: declare variable with let, const, or var let x = 5; console.log(x);
Output
5
Quick Reference
| Feature | Effect in Strict Mode |
|---|---|
| Undeclared variables | Throws ReferenceError instead of creating global variables |
| Deleting variables or functions | Throws SyntaxError |
| Duplicate parameter names | Throws SyntaxError |
| Writing to read-only properties | Throws TypeError |
| Using reserved keywords as identifiers | Throws SyntaxError |
| Octal literals (e.g., 012) | Not allowed, throws SyntaxError |
Key Takeaways
Add 'use strict'; at the top of your script or function to enable strict mode.
Strict mode helps catch common mistakes like undeclared variables and reserved keywords.
Always place 'use strict'; as the first statement to ensure it works correctly.
Strict mode makes JavaScript safer by throwing errors for unsafe actions.
Use strict mode to write cleaner and more reliable JavaScript code.