3 min read
•Question 36 of 50easyWhat is Strict Mode in JavaScript?
Understanding use strict and its effects.
What You'll Learn
- How to enable strict mode
- What it prevents
- Why use it
Enabling Strict Mode
code.jsJavaScript
// For entire script
'use strict';
// For single function
function myFunction() {
'use strict';
// strict mode only in this function
}
// ES6 modules are always in strict modeWhat Strict Mode Prevents
code.jsJavaScript
'use strict';
// 1. Undeclared variables
x = 10; // ReferenceError
// 2. Deleting variables
let y = 1;
delete y; // SyntaxError
// 3. Duplicate parameters
function sum(a, a) { } // SyntaxError
// 4. Octal literals
let num = 010; // SyntaxError
// 5. Writing to read-only properties
const obj = {};
Object.defineProperty(obj, 'x', { value: 1, writable: false });
obj.x = 2; // TypeError
// 6. this in functions is undefined
function test() {
console.log(this); // undefined, not window
}Benefits
| Feature | Without Strict | With Strict |
|---|---|---|
| Undeclared vars | Creates global | Error |
| Silent failures | Ignored | Throws error |
| this in function | window | undefined |
Best Practice
Modern JavaScript (ES6+ modules, classes) is automatically in strict mode. For older code, always use 'use strict'.