🔒 Strict Mode = Fewer Bugs
JavaScript has quirks. Strict mode prevents common mistakes. Safer code, fewer bugs, better performance.
📝 Enabling Strict Mode
// Global strict mode
'use strict';
// Function-level strict mode
function myFunction() {
'use strict';
// Strict code here
}
// In modules (strict by default)
export default function() {
// Already strict
}
// In classes (strict by default)
class MyClass {
// Strict mode enabled
🎯 What Strict Mode Prevents
// ❌ Without strict mode (works, but bug)
x = 10; // Global variable created (accidental)
// ✅ With strict mode (error)
'use strict';
x = 10; // ReferenceError: x is not defined
// ❌ Without strict mode
function sum(a, a, c) { } // Duplicate parameter
// ✅ With strict mode (error)
'use strict';
function sum(a, a, c) { } // SyntaxError
// ❌ Without strict mode
delete Object.prototype; // Silently fails
// ✅ With strict mode (error)
'use strict';
delete Object.prototype; // TypeError
// ❌ Without strict mode
var obj = { get x() { return 1; } };
obj.x = 2; // Silently fails
// ✅ With strict mode (error)
'use strict';
obj.x = 2; // TypeError
// ❌ Without strict mode (works, security risk)
eval('var x = 10');
// ✅ With strict mode (eval is isolated)
'use strict';
eval('var x = 10');
console.log(x); // ReferenceError (x is not defined)
💡 Benefits
- Prevents accidental globals
- Catches syntax errors earlier
- Disables dangerous features (with, eval)
- Better performance (optimized execution)
- Safer code
“Forgot var, created global accidentally. Strict mode catches this. Now I always use strict. Fewer bugs, safer code.”
