Strict Mode
Definition
Strict mode is a way to opt in to a restricted variant of JavaScript, thereby implicitly opting-out of 'sloppy mode'. It intentionally has different semantics from normal code, turning some previously-accepted silent mistakes into actual errors.
Explain Like I'm New
Imagine playing a game where the referee normally lets minor rule breaks slide. Turning on 'Strict Mode' is like telling the referee to blow the whistle for absolutely every foul. It forces you to play cleaner, safer code by complaining when you do sloppy things like using a variable without declaring it.
Real World Example
If you misspell a variable name (like typing `x = 5` when you meant `let X = 5`), sloppy mode will just silently create a new global variable called `x`. Strict mode will crash and tell you 'x is not defined', saving you hours of debugging.
Common Use Cases
- •Preventing accidental global variables
- •Making debugging easier by throwing errors instead of silently failing
- •Preparing code for future versions of ECMAScript (disallows future reserved keywords)
Interactive Example
Interview Questions
basic
- How do you enable strict mode?
- What is 'sloppy mode'?
intermediate
- Name three things that are allowed in sloppy mode but throw an error in strict mode.
- Can you enable strict mode for just one specific function?
advanced
- How does strict mode affect the 'this' keyword?
- Are ES6 modules and classes strictly evaluated by default?
trick
- If you concatenate two scripts, one with strict mode and one without, what happens?