⚡ Strict Mode = Better Code
JavaScript is forgiving. Strict mode is strict. Catch errors early, write better code.
📝 Strict Mode Basics
// Enable for entire script
"use strict";
// Enable for function only
function strictFunction() {
"use strict";
// strict code
}
// Examples of strict mode
// 1. Cannot use undeclared variables
// Bad (without strict)
x = 10; // Creates global variable
// Good (strict)
"use strict";
x = 10; // ReferenceError
// 2. Cannot delete variables
"use strict";
var x = 5;
delete x; // SyntaxError
// 3. Duplicate parameter names
// Bad (without strict)
function add(a, a) { return a + a; }
// Good (strict)
"use strict";
function add(a, b) { return a + b; }
// 4. Octal literals
"use strict";
var num = 010; // SyntaxError
// 5. with statement
"use strict";
with (obj) { } // SyntaxError
🎯 Strict Mode Benefits
// 1. Prevents accidental globals
function strictFunction() {
"use strict";
undeclared = 5; // ReferenceError
}
// 2. Prevents duplicate property names
"use strict";
var obj = {
prop: 1,
prop: 2 // SyntaxError
};
// 3. Prevents octal notation
"use strict";
var num = 012; // SyntaxError
// 4. Prevents delete on variables
"use strict";
var x = 5;
delete x; // SyntaxError
// 5. Makes eval safer
"use strict";
eval('var x = 5');
console.log(x); // ReferenceError
// 6. Prevents this from being global
function strictFunc() {
"use strict";
console.log(this); // undefined
}
// 7. Reserves keywords
"use strict";
var private = 5; // SyntaxError
// 8. Improves performance
// Some optimizations enabled
// Strict Mode Tips
- Enable by default
- Prevents common errors
- Catch bugs early
- Better performance
- Essential for modern JS
💡 Strict Mode Tips
- Enable by default
- Prevents common errors
- Catch bugs early
- Better performance
- Essential for modern JS
“Strict mode writes better code. Catch errors early, improve quality. Essential for modern JavaScript.”
