JavaScript Course
JavaScript
/
Beginner

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

Loading...
Console output will appear here...

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?

Flash Cards

Question

How do you enable strict mode?

Click to reveal answer
Answer

By placing the exact string `"use strict";` at the very top of a script file, or at the top of a specific function body.

Question

How does strict mode affect the 'this' keyword?

Click to reveal answer
Answer

In sloppy mode, if 'this' is undefined or null in a function, it defaults to the global object (window in browsers). In strict mode, 'this' remains undefined.

Question

Are ES6 modules strictly evaluated by default?

Click to reveal answer
Answer

Yes. The entire contents of JavaScript modules (import/export) and Classes are automatically in strict mode, with no statement needed.