Strict mode is a safer version of JavaScript that turns silent mistakes into real errors. You turn it on by writing 'use strict' at the top of a script or a function. ES modules and class bodies are always strict.
The main differences:
- Assigning to a variable you never declared throws a
ReferenceError. Without strict mode, it silently creates a global variable. - In a plain function call like
f(),thisisundefinedinstead of the global object. - Primitives passed as
thisare not boxed. Boxing means wrapping a primitive like42in an object likenew Number(42). - Writes that would fail silently now throw a
TypeError. Examples are writing to a read-only or frozen property, or adding a property to a non-extensible object. - Duplicate parameter names, the
withstatement and old octal literals like010are syntax errors. evalcannot add variables to the surrounding scope.
The goal is to show mistakes early as errors. It also lets engines optimize the code more safely.
- You turn on strict mode per script or per function. Modules and classes are strict automatically.
- Assigning to an undeclared variable throws a
ReferenceError. thisisundefinedin a plain function call.- Silent failures, like writing to a frozen or read-only property, become a
TypeError. with, duplicate parameter names and old octal literals are not allowed.
Read more