What is the purpose of ‘use strict’ in JavaScript?

The purpose of “use strict” is to indicate that the code should be executed in “strict mode”. Strict mode is a way to opt in to a restricted variant of JavaScript. Strict mode eliminates some JavaScript silent errors by changing them to throw errors.

For example, in strict mode, assigning a value to a non-writable property will throw an error:

“use strict”;

var obj = {};
Object.defineProperty(obj, “x”, { value: 42, writable: false });

obj.x = 9; // throws an error in strict mode

What is the purpose of the “use strict” directive?

The “use strict” directive is used to enable strict mode, which is a way of writing JavaScript code that helps to prevent errors and improve safety. It enforces stricter rules for code, which can help to prevent certain types of errors.

For example, consider the following code:

function myFunction() {
x = 10;
}

myFunction();

console.log(x); // prints 10

Without strict mode, this code would execute without any errors. However, when using strict mode, the code will throw an error because the variable x was not declared before it was used.

“use strict”;

function myFunction() {
x = 10; // throws an error
}

myFunction();