Chapter 17 of 49

JavaScript Strict Mode

JavaScript was designed to be forgiving. If you make certain mistakes, it doesn't stop you. It quietly guesses what you meant and keeps going. That sounds friendly, but it often hides bugs until much later.

Look at this function. Can you spot the problem?

function calculateTotal(price, quantity) {
    totl = price * quantity; // typo: should be "total"
    return totl;
}

console.log(calculateTotal(50, 3));
console.log(totl); // oops, a global variable was created

Output:

150
150

We never declared totl, yet there's no error. JavaScript silently created a global variable called totl. In a big program, that accidental global can clash with another variable and cause a bug that is very hard to track down.

Strict mode turns silent mistakes like this into clear errors. In this chapter, we'll see how to turn it on, exactly what it changes, and why modern JavaScript uses it almost everywhere.

What is Strict Mode?

Strict mode is an opt-in, restricted version of JavaScript that throws errors for some unsafe actions that normal JavaScript silently allows, and forbids a few confusing features.

It was added in ES5 (2009). The normal, forgiving mode is often informally called sloppy mode.

Think of it like a teacher who used to ignore spelling mistakes and now underlines every one in red. Your essay is the same, but now you find the mistakes early, while they're easy to fix.


Turning On Strict Mode

You enable strict mode by writing the string "use strict"; as the very first statement. Single quotes ('use strict';) work too. This special string is called a directive.

For a Whole Script

Put it at the top of the file:

"use strict";

function calculateTotal(price, quantity) {
    totl = price * quantity; // typo: should be "total"
    return totl;
}

console.log(calculateTotal(50, 3));

Output:

ReferenceError: totl is not defined

The program stops at the typo and tells us exactly what's wrong. That is the whole point of strict mode.

For a Single Function

Put it as the first statement inside the function body. Only that function (and any functions written inside it) becomes strict:

function sloppyFunction() {
    city = "Delhi"; // no error: creates a global variable
    console.log("sloppy:", city);
}

function strictFunction() {
    "use strict";
    country = "India"; // ReferenceError
    console.log("strict:", country);
}

sloppyFunction();
strictFunction();

Output:

sloppy: Delhi
ReferenceError: country is not defined

It Must Come First

The directive only works at the start of a script or function. Comments and blank lines before it are fine, but any real statement before it turns it into an ordinary string that does nothing:

let count = 1;
"use strict"; // too late: this is just a string, ignored

score = 100; // no error, so strict mode is NOT on
console.log(score);

Output:

100

There is also no way to make just one block (like an if block or a loop) strict. It's either the whole script or a whole function.

Places That Are Strict Automatically

In modern JavaScript you often get strict mode without writing the directive at all:

Code

Strict mode?

A normal <script> or a Node.js CommonJS file

Only if you write "use strict";

Code inside a class body

Always (automatically)

JavaScript modules (type="module", .mjs, files using import/export)

Always (automatically)

A function written inside strict code

Yes, strictness is inherited from the surrounding code

We'll study classes and modules in later chapters. For now, just remember: if you write modern code with classes or modules, you are already in strict mode.

How Can I Check?

A small trick: in strict mode, a plain function call gets this as undefined (the this keyword chapter explains why).

// A comment before the directive is fine
"use strict";

function isStrictMode() {
    return this === undefined;
}

console.log(isStrictMode());

Output:

true

Remove the directive and the same program prints false.


What Strict Mode Changes

Strict mode makes three kinds of changes:

1. Silent mistakes        →  now throw errors
2. Confusing features     →  now forbidden (SyntaxError before the code even runs)
3. Some unsafe behaviour  →  made safer (this, eval)

Let's go through the important ones. The error messages shown are the ones printed by Chrome and Node.js (both use the V8 engine); other browsers use different wording for the same errors.

1. No Accidental Global Variables

This is the most useful rule. Assigning to a variable that was never declared throws a ReferenceError instead of creating a global variable, as we saw with totl. Always declare variables with let or const.

2. Assignments That Silently Failed Now Throw

In sloppy mode, some assignments just don't happen, without any warning:

undefined = 5; // silently ignored
console.log(undefined);

Output:

undefined

The assignment was ignored, and you'd never know. In strict mode, the same line throws:

"use strict";

undefined = 5;

Output:

TypeError: Cannot assign to read only property 'undefined' of object '#<Object>'

(This is the Node.js message. In Chrome, the global object is a Window, so the end reads '#<Window>' instead.)

The same happens with NaN and Infinity, and with adding a property to a primitive value:

"use strict";

let name = "Riya";
name.nickname = "Ri"; // a string can't hold properties

Output:

TypeError: Cannot create property 'nickname' on string 'Riya'

Later you'll meet more cases of this rule: writing to a frozen object (Object Methods chapter) or to a getter-only property (Classes chapter) is silently ignored in sloppy mode but throws a TypeError in strict mode.

3. No Duplicate Parameter Names

function sum(a, a) {
    return a + a;
}

console.log(sum(1, 2));

Output (sloppy mode):

4

The second a silently hides the first, so we get 2 + 2. That's almost certainly a typo. In strict mode, this is rejected before the code runs:

SyntaxError: Duplicate parameter name not allowed in this context

4. No Old-Style Octal Numbers

In sloppy mode, a number starting with 0 may be read as octal (base 8):

let n = 010;
console.log(n);
console.log(0o10); // the modern, clear way to write octal

Output:

8
8

Someone typing a PIN or a roll number like 010 would get 8. Strict mode forbids the confusing form:

SyntaxError: Octal literals are not allowed in strict mode.

If you really want octal, write 0o10, which works in both modes.

5. this Is undefined in Plain Function Calls

In sloppy mode, a function called on its own gets the global object as this. In strict mode it gets undefined. This prevents functions from accidentally reading or creating global variables through this. We'll explore this properly in the this Keyword chapter.

6. Functions Declared in Blocks Stay in the Block

The Hoisting chapter warned that function declarations inside if blocks behave differently in different modes. In strict mode the rule is simple: the function is block-scoped, like a let variable.

"use strict";

if (true) {
    function sayHi() {
        console.log("Hi");
    }
    sayHi(); // works inside the block
}

sayHi(); // ReferenceError in strict mode

Output:

Hi
ReferenceError: sayHi is not defined

Without "use strict", the second call also prints Hi, because sloppy mode leaks the function out of the block for backward compatibility.

7. Smaller Rules

  • Deleting a variable is a SyntaxError. delete x; on a plain variable is not allowed (delete is only for object properties).

  • The with statement is forbidden. It made it impossible to know which variable a name referred to just by reading the code.

  • eval() can't create variables outside itself. In strict mode, eval("var secret = 42;") keeps secret inside the eval, so typeof secret afterwards is "undefined" (in sloppy mode it's "number").

  • eval and arguments can't be used as variable names.

  • More reserved words. let, static, yield, implements, interface, package, private, protected and public can't be used as variable names. var public = 1; works in sloppy mode but is a SyntaxError in strict mode.


Sloppy Mode vs Strict Mode

Situation

Sloppy mode

Strict mode

Assign to an undeclared variable

Creates a global variable

ReferenceError

Assign to undefined, NaN, a read-only property

Silently ignored

TypeError

Add a property to a primitive ("hi".x = 1)

Silently ignored

TypeError

Duplicate parameter names

Allowed (last one wins)

SyntaxError

Octal literal 010

Means 8

SyntaxError

this in a plain function call

Global object

undefined

Function declared inside a block

Leaks out of the block

Block-scoped

with statement

Allowed

SyntaxError

delete a plain variable

Returns false

SyntaxError

Reassigning a const

TypeError

TypeError (no change)

Notice the last row: some rules, like const protection, are the same in both modes. Strict mode doesn't change everything; it mainly removes the "silent" behaviour.


A Trap: Default Parameters and "use strict"

If a function uses default values, rest parameters or destructuring in its parameter list, you are not allowed to put "use strict" inside it:

function greet(name = "Guest") {
    "use strict";
    return "Hello, " + name;
}

Output:

SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list

The reason: the parameters are processed before the function body runs, so it would be unclear whether the default values should follow strict rules or not. The fix is easy: put "use strict"; at the top of the file instead, and the function inherits it.


A Trap: Joining Files Together

Build tools often join many script files into one. Since "use strict" only works at the very top, joining can quietly change behaviour:

a.js: "use strict"; ...      b.js: (sloppy code) ...

a.js + b.js  →  "use strict" is at the top
                → b.js's code is now strict too, and may break

b.js + a.js  →  "use strict" is now in the middle
                → it's ignored, and a.js is no longer strict

This is one reason people used to wrap each file in a function with its own "use strict". Today, modules solve this cleanly, because every module is strict on its own.


Why Use Strict Mode?

  • Catches bugs early. Typos in variable names become errors right away instead of hidden globals.

  • Makes failures loud. An assignment that doesn't work throws instead of being ignored.

  • Safer this. A function called the wrong way can't accidentally touch the global object.

  • Easier for engines to optimise. Removing features like with means the engine can know at a glance which variable each name refers to.

  • Prepares for the future. Words like private and public are reserved so the language can use them later.

Strict mode doesn't make your code slower, and for everyday code that is already correct, the behaviour is usually exactly the same. If your code works in strict mode, it's very likely better code.


Common Mistakes

  • Putting the directive below other code. It must be the first statement of the script or function, otherwise it's silently ignored.

  • Trying to make one block strict. Only whole scripts and whole functions can be strict.

  • Using "use strict" inside a function with default parameters. That's a SyntaxError; put it at the file level instead.

  • Thinking strict mode is a different language. It's the same JavaScript with some unsafe parts switched off. Correct code usually runs the same in both modes.

  • Adding "use strict" to modules or classes. It's harmless, but unnecessary; they are already strict.

  • Misspelling it. "use-strict" or "Use strict" are just strings and do nothing.


Interview Tips

A good short answer to "What is strict mode?":

"Strict mode, added in ES5, is enabled with the "use strict" directive at the top of a script or function. It turns silent errors into thrown errors, for example assigning to an undeclared variable throws a ReferenceError instead of creating a global. It also forbids things like duplicate parameter names, octal literals and with, and makes this undefined in plain function calls. ES modules and class bodies are always strict."

Questions interviewers like to ask:

  • "What does x = 10 do without declaring x?" Sloppy mode: creates a global. Strict mode: ReferenceError.

  • "What is this inside a plain function call?" Global object in sloppy mode, undefined in strict mode.

  • "Can you enable strict mode for one block?" No, only for a whole script or function.

  • "Do I need "use strict" in a React project / ES module?" No, modules are strict automatically.

  • "Why can't I use "use strict" in function f(a = 1)?" Functions with non-simple parameters can't contain the directive.

Practice: predict the output (or error) of each snippet, with and without "use strict" at the top: function f(){ y = 5; } f(); console.log(y);, then console.log(012);, then NaN = 3; console.log(NaN);.

Conclusion

Strict mode is a safer version of JavaScript that turns silent mistakes into clear errors.

  • Turn it on with "use strict"; as the first statement of a script or function.

  • Classes and modules are always strict automatically.

  • Assigning to an undeclared variable throws a ReferenceError instead of creating a global.

  • Assignments that used to fail silently now throw a TypeError.

  • Duplicate parameters, octal literals like 010, with and deleting variables are forbidden.

  • this in a plain function call is undefined, not the global object.

From now on, it's a good habit to write code that works in strict mode. You'll see its effects again when we study objects, the this keyword, classes and modules.