"use strict" directive explained for JavaScript

"use strict" — tiny directive, big impact. 🚀 If you’ve written JS for a while you’ve probably seen: "use strict"; Placed at the top of a file or function, it flips JavaScript into a stricter mode that helps catch mistakes early and avoids some weird legacy behaviors. Why use it? ✅ Turns silent errors into thrown errors (helps you catch bugs sooner). ✅ Prevents accidental globals — assignment to an undeclared variable throws. ✅ Disallows duplicate parameter names and deprecated features (like with). ✅ Makes optimizations more predictable for engines. Bonus: ES modules (import/export) are strict by default — no need to add it there. Quick example: // Non-strict — creates a global by accident function bad() { x = 10; } bad(); // x is now global // Strict — throws, so you fix it function good() { "use strict"; x = 10; // ReferenceError: x is not defined } Best practice: Prefer ES modules (they’re strict by default). If using scripts, put "use strict"; at the top of the file. Don’t assume it prevents all unsafe behavior — it helps, but write clear, tested code. Have you run into a bug that "use strict" would’ve caught? Share below — always fun to learn from real mistakes. 👇 #javascript #webdev #frontend #bestpractices

To view or add a comment, sign in

Explore content categories