Strict Mode
Overview
Strict mode is a way to opt in to a restricted variant of JavaScript. It was introduced in ES5 (2009).
JavaScript historically allowed developers to write 'sloppy' code (like using variables without declaring them). Strict mode eliminates some JavaScript silent errors by changing them to throw actual errors, helping you write more secure and robust code.
Syntax
Simply place the string "use strict"; at the very top of your file or function. It looks like a simple string, but the engine treats it as a special directive.
"use strict";
// Now, using an undeclared variable throws an error!
x = 3.14; // Uncaught ReferenceError: x is not definedYou can enable strict mode for an entire script, or just inside a specific function.
x = 3.14; // Works fine (sloppy mode)
function myFunc() {
"use strict";
y = 3.14; // Throws an error!
}Common Pitfalls
- In strict mode,
thisisundefinedin global functions instead of pointing to thewindowobject. This trips up many developers. - You cannot use reserved words for future versions (like
public,private,interface) as variable names in strict mode.
Interview Questions
'use strict' is a directive introduced in ES5 that enforces stricter parsing and error handling in JavaScript. It prevents accidental global variables, throws errors for silent failures, and disables some confusing features like the 'with' statement.
Yes! Any file that is treated as an ES6 Module (using import/export) is automatically in strict mode. You don't need to explicitly write 'use strict'.
Real-World Example
If you are working in modern React, Angular, or writing ES6 modules, strict mode is enabled automatically. It prevents you from accidentally polluting the global scope with undeclared variables.
// Inside a React file or ES6 Module
// "use strict" is active automatically behind the scenes
const calculateTotal = (price) => {
tax = 0.2; // ReferenceError! You forgot 'let' or 'const'
return price + (price * tax);
}Check Your Knowledge
Test your understanding of Strict Mode with these quick questions.