JavaScript Strict Mode

JavaScript Strict Mode
Strict Mode is a feature in JavaScript that helps you write cleaner, safer, and error-free code by enforcing stricter rules.
To enable strict mode, add the line:
at the top of a script or function.
Why Use Strict Mode?
Strict mode:
- Prevents the use of unsafe code
- Avoids common mistakes
- Makes debugging easier
- Improves performance in some engines
Example 1: Using Strict Mode in Script
Without strict mode, this would create a global variable automatically.
Example 2: Strict Mode in a Function
What Strict Mode Disallows
| Action | Allowed Normally | Allowed in Strict Mode |
|---|---|---|
| Using undeclared variables | Yes | No |
| Deleting variables | Sometimes | No |
| Duplicate parameter names | Yes | No |
Using eval() to create variables | Yes | No |
| Using keywords as variable names | Yes | No |
Example: Duplicate Variables Not Allowed
Reserved Keywords Cannot Be Used as Variables
this Behavior Changes
In strict mode, this inside a function is undefined (not the global object).
Summary
| Feature | Strict Mode Effect |
|---|---|
| Prevents accidental globals | Yes |
| Disallows unsafe syntax | Yes |
| Helps avoid silent errors | Yes |
| Makes code more secure | Yes |
