What Does "use strict" Do in JavaScript?

Strict mode in JavaScript makes JavaScript more strict about handling common mistakes. You should enable strict mode unless you have a good reason not to.

To enable strict mode, put the string 'use strict' as the first statement in a file or function.

;

function foo ( ) { ; }

var x = 1 ; ;

Here are some of the major benefits of using strict mode:

ReferenceError for Undeclared Variables

Outside of strict mode, the below code implicitly creates a global variable x .

function foo ( ) { x = 42 ; } foo(); x;

With strict mode, setting x = 42 without first declaring x using let or var will throw an error:

; function foo ( ) { x = 42 ; } foo();

this Defaults to undefined

When you call a function that isn't bound to any object outside of strict mode, this will be the global object. Pretty counter-intuitive, right?

const foo = function ( ) { console .log( this ); }; foo();

With strict mode, this will be undefined .

; const foo = function ( ) { console .log( this ); }; foo();

Enforcing Read-Only Properties

The Object.freeze() function makes a JavaScript object immutable. You can't add or remove properties, or modify existing properties, on a frozen object.

Unfortunately, Object.freeze() has a big gotcha: it only works if the code attempting to modify the object is in strict mode. Outside of strict mode, if you try to modify a frozen object, the JavaScript runtime will let it go.

const frozen = function ( ) { ; return Object .freeze({ answer : 42 }); }; const unstrict = function ( ) { const obj = frozen(); obj.answer = 43 ; console .log(obj.answer); }; const strict = function ( ) { ; const obj = frozen(); obj.answer = 43 ; }; unstrict(); strict();

No Setting Properties on Primitives

Outside of strict mode, setting a property on a number fails silently.

let answer = 42 ; answer.prop = 'test' ; console .log(answer.prop);

In strict mode, setting a property on a number throws a TypeError .

; let answer = 42 ; answer.prop = 'test' ;

Prevent Deleting prototype

Outside of strict mode, deleting an undeletable property fails silently:

delete Object .prototype; const obj = { answer : 42 }; console .log(obj.constructor.prototype);

In strict mode, deleting prototype throws a TypeError :

; delete Object .prototype;

More Fundamentals Tutorials