JavaScript Notes
Learn JavaScript strict mode (
JavaScript has a "sloppy" default mode that silently ignores many mistakes to stay backward-compatible with old code. Strict mode turns on a stricter set of rules that catch real bugs early — turning silent failures into loud errors. It's one of the best practices you can adopt from day one.
Real World Analogy
Imagine a car without seatbelt warnings vs. one with warnings. The car without warnings (sloppy mode) lets you drive without your seatbelt — it won't stop you. The car with warnings (strict mode) beeps loudly every time you forget the seatbelt, preventing a potentially dangerous mistake.
Strict mode is JavaScript's seatbelt warning system.
How to Enable Strict Mode
Option 1: Globally in a script file
"use strict"; // must be the VERY FIRST statement in the file
let name = "Rahul";
console.log(name);Rahul
Option 2: Inside a specific function only
function strictFunction() {
"use strict"; // only applies inside this function
// strict rules apply here
}
function sloppyFunction() {
// strict rules do NOT apply here
}Option 3: Automatically in ES6 Modules
// Any file with import or export is AUTOMATICALLY in strict mode
// You don't need to write "use strict" — it's always on
import { add } from './math.js'; // This file is strict by defaultOption 4: Automatically in Classes
// Class bodies are always in strict mode — no need to declare it
class User {
constructor(name) {
this.name = name; // strict mode is always active here
}
}What Strict Mode Changes — Internal Model
What Strict Mode Prevents — With Code Examples
1. Using undeclared variables
// WITHOUT strict mode
city = "Mumbai"; // silently creates a global variable
console.log(city); // works — but a hidden global pollutes your code!Mumbai
// WITH strict mode
"use strict";
city = "Mumbai"; // ❌ ReferenceError: city is not definedReferenceError: city is not defined
2. Deleting a variable (or a function)
"use strict";
let score = 100;
delete score; // ❌ SyntaxError in strict modeSyntaxError: Delete of an unqualified identifier in strict mode.
3. Duplicate parameter names in functions
// Without strict mode — silently allowed (last one wins)
function badFunc(a, a) {
console.log(a); // which 'a'? confusing!
}
badFunc(1, 2); // 22
// With strict mode — error!
"use strict";
function badFunc(a, a) { // ❌ SyntaxError
console.log(a);
}SyntaxError: Duplicate parameter name not allowed in this context
4. Writing to read-only properties
"use strict";
const obj = {};
Object.defineProperty(obj, "name", { value: "WoHoTech", writable: false });
obj.name = "Something Else"; // ❌ TypeError in strict modeTypeError: Cannot assign to read only property 'name' of object
Without strict mode, this assignment would silently fail with no error.
5. this is undefined in plain functions
This is one of the most important differences — it prevents bugs with this:
// Without strict mode
function showThis() {
console.log(this); // the global object (window in browser) — risky!
}
showThis();Window { ... } (the global object)// With strict mode
"use strict";
function showThis() {
console.log(this); // undefined — much safer!
}
showThis();undefined
6. Reserved words as variable names
"use strict";
let implements = 5; // ❌ SyntaxError — future reserved word
let private = "data"; // ❌ SyntaxError — future reserved word
let static = true; // ❌ SyntaxErrorSyntaxError: Unexpected strict mode reserved word
7. eval and arguments as variable names
"use strict";
let eval = 10; // ❌ SyntaxError
let arguments = []; // ❌ SyntaxErrorSyntaxError: Unexpected eval or arguments in strict mode
Sloppy Mode vs Strict Mode — Comparison Table
| Feature / Code | Sloppy Mode | Strict Mode |
|---|---|---|
Undeclared variable x = 5 | Creates global silently | ReferenceError |
Duplicate params f(a, a) | Silently allowed | SyntaxError |
delete variable | Silently fails | SyntaxError |
| Write to read-only prop | Silently fails | TypeError |
this in plain function | Global object | undefined |
| Future reserved words as vars | Allowed | SyntaxError |
eval as var name | Allowed | SyntaxError |
arguments as var name | Allowed | SyntaxError |
with statement | Allowed | SyntaxError |
Octal literals 012 | Allowed | SyntaxError |
Does Strict Mode Apply Automatically?
Common Mistakes
❌ Mistake 1: Placing "use strict" after code
// ❌ WRONG — "use strict" must be FIRST
let x = 10;
"use strict"; // TOO LATE — this is treated as a plain string, not a directive!
undeclaredVar = 5; // No error — strict mode never activated!// ✅ CORRECT — first line of the file or function
"use strict";
let x = 10;
undeclaredVar = 5; // ❌ ReferenceError (as expected)❌ Mistake 2: Expecting strict mode to prevent all runtime errors
"use strict";
// Strict mode doesn't prevent logic errors:
function divide(a, b) {
return a / b; // still returns Infinity if b is 0, no error!
}
console.log(divide(10, 0)); // Infinity — strict mode can't help with this❌ Mistake 3: Forgetting strict mode in legacy code mixed with modules
When you mix old <script> tags with ES6 modules, each file may have different strictness. Always be explicit about which files should be strict.
Key Takeaways
"use strict"activates a stricter set of JavaScript rules- It must be the first statement in the file or function to take effect
- It turns silent bugs into loud errors — catching mistakes early
- Key protections: no undeclared variables, no duplicate params,
thisisundefinedin plain functions - ES6 modules and class bodies are always strict — no declaration needed
- Strict mode helps JavaScript engines optimize your code (can be faster)
- Writing modern code (classes, modules, arrow functions)? You're already in strict mode
- Always use strict mode in new JavaScript files — it's a universal best practice
Interview Questions & Answers
Q1. What is strict mode in JavaScript and how do you enable it?
Answer: Strict mode is an opt-in feature that enforces a stricter interpretation of JavaScript, catching common mistakes and turning silent failures into explicit errors. Enable it by placing the string "use strict"; as the first statement in a script file or function body. ES6 modules and class bodies are automatically in strict mode.
Q2. What happens when you use an undeclared variable in strict mode?
Answer: A ReferenceError is thrown immediately. In sloppy (non-strict) mode, assigning to an undeclared variable silently creates a global variable — a common source of hard-to-find bugs. Strict mode prevents this by requiring all variables to be explicitly declared with var, let, or const.
Q3. What does this equal inside a regular function in strict mode?
Answer: In strict mode, this inside a regular function called without a specific context is undefined. In sloppy mode, it defaults to the global object (window in browsers, global in Node.js). This strict behavior prevents accidental modification of the global object through this.
Q4. Does placing "use strict" after some code work?
Answer: No. The "use strict" directive must be the very first statement in the file or function. If placed after any executable code, it's treated as a plain string expression (which is valid JS but does nothing). Strict mode is never activated in that case.
Q5. Are ES6 modules automatically in strict mode?
Answer: Yes. Any JavaScript file that uses ES6 module syntax (import/export) is automatically treated as a strict mode module. You don't need to add "use strict" manually. Similarly, class bodies are always in strict mode regardless of the surrounding code.
Q6. Can you turn off strict mode for just one function inside a strict-mode file?
Answer: No — once strict mode is enabled at the file level, you cannot opt out of it for specific functions within that file. You can, however, enable strict mode for only one function (by placing "use strict" inside just that function) while keeping the rest of the file in sloppy mode.
Q7. What is the benefit of strict mode for performance?
Answer: Strict mode eliminates certain ambiguous patterns (like with statements and eval scope manipulation) that make it impossible for JavaScript engines to statically analyze code. Without these patterns, the engine can apply more aggressive optimizations (like inlining, dead code elimination, and variable layout optimization), potentially making strict mode code faster.
Q8. What are "future reserved words" and why does strict mode block them?
Answer: Future reserved words are identifiers that the ECMAScript specification has reserved for potential future language features: implements, interface, package, private, protected, public, static. In strict mode, using these as variable names throws a SyntaxError. This prevents code from breaking when these keywords are eventually implemented in the language.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript Strict Mode Complete Guide – .
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, basics, strict, mode
Related JavaScript Master Course Topics