Newsletter

JavaScript strict mode: what it changes and how to enable it

JavaScript strict mode: what it changes and how to enable it

What is strict mode?

Strict mode was introduced in ECMAScript 5 (ES5). It is a stricter, more restricted variant of JavaScript that raises errors for mistakes that are usually handled in silence. For example, in non-strict mode, if you initialise a variable without declaring it with the var keyword (x = 5, for instance), the JavaScript interpreter assumes you meant a global variable, and if that variable did not exist it creates one for you.

Deprecated functions can raise errors in strict mode as well. Strict mode therefore cuts down on bugs and improves both the security and the overall performance of your application.

Turning strict mode on

To turn strict mode on, all you have to do is add the string “use strict” at the top of your script, as in the following example:

javascript
"use strict";
x = 5; // ReferenceError: x is not defined
console.log(x);

If you add the “use strict” directive as the first line of your JavaScript program, strict mode applies to the whole script. You can also turn strict mode on inside a single function, like this:

javascript
x = 5;
console.log(x); // 5
function sayHello() {
    "use strict";
    str = "Hello World!"; // ReferenceError: str is not defined
    console.log(str);
}
sayHello();

Worth knowing: the “use strict” directive is only recognised at the start of a script or of a function. Every modern browser supports the “use strict” directive except Internet Explorer 9 and below. Browsers that do not support it ignore it silently and parse the JavaScript in non-strict mode.

The general restrictions of strict mode

Strict mode changes both the syntax and the runtime behaviour. In the sections below we go through the general restrictions it applies:

Undeclared variables are not allowed

As you already know, every variable has to be declared in strict mode. If you assign a value to an identifier that is not a declared variable, a ReferenceError is thrown.

javascript
"use strict";

function doSomething() {
    msg = "Hello world!"; // ReferenceError: msg is not defined
    return msg;
}
console.log(doSomething());

Deleting a variable or a function is not allowed

In strict mode, trying to delete a variable or a function raises a syntax error. In non-strict mode such an attempt fails silently and the delete expression evaluates to false.

javascript
"use strict";
var person = {name: "Damien", age: 25};
delete person; // SyntaxError

In the same way, trying to delete a function in strict mode gives you a syntax error:

javascript
"use strict";
function sum(a, b) {
    return a + b;
}
delete sum; // SyntaxError

Duplicate parameter names are not allowed

In strict mode, a syntax error is raised when a function declaration has two or more parameters with the same name. In non-strict mode, no error occurs.

javascript
"use strict";

function test(a, a) { // SyntaxError
    return a * a;
}
console.log(square(2, 2));

eval() cannot change the surrounding scope

In strict mode, for security reasons, code passed to eval() cannot declare or change variables, nor define functions, in the surrounding environment the way it can in non-strict mode.

javascript
"use strict";
eval("var x = 5;");
console.log(x); // ReferenceError: x is not defined

eval and arguments cannot be used as identifiers

In strict mode, the names eval and arguments are treated as keywords, so they cannot be used as variable names, function names, function parameter names, and so on.

javascript
"use strict";
var eval = 10; // SyntaxError
console.log(eval);

The with statement is not allowed

In strict mode, the with statement is not allowed. The with statement adds the properties and the methods of an object to the current scope. Statements nested inside a with block can therefore call those properties and methods directly, without referring to the object.

javascript
"use strict";

// Without with
var radius1 = 5;
var area1 = Math.PI * radius1 * radius1;

// Using with
var radius2 = 5;
with(Math) { // SyntaxError
    var area2 = PI * radius2 * radius2;
} 

Writing to a read-only property is not allowed

In strict mode, assigning a value to a non-writable property, to a getter-only property or to a property that does not exist throws an error. In non-strict mode, those attempts fail silently.

javascript
"use strict";

var personne = {name: "Damien", age: 25};

Object.defineProperty(personne, "genre", {value: "homme", writable: false});
personne.genre = "femme"; // TypeError

Adding a new property to a non-extensible object is not allowed

In strict mode, attempts to create new properties on non-extensible or non-existent objects throw an error too. In non-strict mode, those attempts fail silently.

javascript
"use strict";

var person = {name: "Damien", age: 25};

console.log(Object.isExtensible(personne)); // true
Object.freeze(personne); //  lock down the personne object
console.log(Object.isExtensible(personne)); // false
personne.genre = "homme"; // TypeError

Octal numbers are not allowed

In strict mode, octal numbers (digits preceded by a zero, 010 or 0377 for example) are not allowed. They are supported by every browser in non-strict mode, though. In ES6, octal numbers are supported by prefixing the number with 0o, that is 0o10, 0o377, and so on.

javascript
"use strict";

var x = 010; // SyntaxError
console.log(parseInt(x));

The examples above show clearly how strict mode helps you avoid the common mistakes that so often go unnoticed while you are writing a JavaScript program.

Keywords reserved for the future are not allowed

Strict mode restricts the use of the keywords that are reserved for future versions of the language.

According to the latest ECMAScript 6 (or ES6) standard, these are reserved keywords in strict mode: await, implements, interface, package, private, protected, public, and static. For the best compatibility, though, you should avoid using reserved keywords as variable names or function names anywhere in your program.

Tip: reserved words, also called keywords, are special words that are part of the JavaScript syntax, such as var, if, for, function, and so on.

···

JavaScript

Damien Flandrin Web developer since 2010, creator of Gekkode and Email Impact. Every article is tested on a real project before publication. Contact
Newsletter

New tests, tutorials and projects, by e-mail.

Reproducible tests, versioned code, dated results. Never any spam.