jsRant asked this 2 years ago

What is the purpose of "use strict" in Javascript?

Some of the javascript codebase that I am working on has 

"use strict";

What is the use of this?

Remy Pereira 2 years ago

Attempts to use eval() to assign value to variables or object properties fails.

Also new variables cannot be introduced using eval()

Also variables and functions inside eval() are not created in the containing scope, they exist locally to the eval()
ben100 2 years ago

If you apply strict mode, some of the errors that would go unnoticed, will get attention.

Eg: object properties with duplicate names, attempt to assign values to undefined variables

In non-strict mode, any atempt to assign value to undefined variable will result in global variable getting created and assigned that value.

The strict mode is a new feature in ECMAScript 5.

Remy Pereira 2 years ago
1 like

Some assignments that fail silently, generates errors in strict mode.

Adding a property to non extensible object.

var myObj = new Object();
myObj.name = "Jamie";

In strict mode this results in error:

SCRIPT5046: Cannot create property for a non-extensible object

Similarly writing to a read-only property raises an error:

SCRIPT5045: Assignment to read-only properties is not allowed in strict mode

ben100 2 years ago
1 like

Inside a function if a is not defined and you say

a = 5;

it creates a global variable a

But in strict mode this leads to error:

Uncaught ReferenceError: a is not defined(…)

ben100 2 years ago

this of null or undefined are coerced to global in normal mode. In strict mode there is no such linking to global.