Use strict in JavaScript

In JavaScript, `\“use strict\“` is a command that turns on strict mode, an option to use more limited version of JavaScript. It was added to ECMAScript 5 and is intended to make JavaScript perform better and to check for errors more thoroughly by requiring stricter parsing and error checking.

When you implement strict mode, some actions normally permitted in non-strict mode will cause exceptions. This will allow developers to identify frequent mistakes and block potentially problematic features from being used. Some of the most important elements of strict mode are:

Features of strict mode:

1. Prevents the use of undeclared variables: In non-strict mode, assigning a value to an undeclared variable creates a global variable. In strict mode, this throws an error, helping to avoid accidental global variable creation.

"use strict";
x = 10; // Throws an error

2. Prevents `this` coercion: Strict mode ensures the value of `this` as assigned upon initial entry into execution context. It avoids the pitfall of the `this` keyword being coerced to the global object.

"use strict";
function myFunction() {
    console.log(this); // `this` is undefined, not the global object
}
myFunction();

3. Forbids duplicate parameter names: Duplicate parameter names are permissible in non-strict modewhere it creates confusion. Strict mode raises an error if a function contains duplicate parameter names.

"use strict";
function sum(a, a, c) { // Throws an error
    return a + a + c;
}

4. Prohibits octal literals: Octal literals (numbers beginning with `0`) are prohibited in strict mode.

"use strict";
var num = 010; // Throws an error

5. Errors on assignment to non-writable properties: In strict mode, attempting to assign a value to a non-writable property results in an error.

"use strict";
var obj = {};
Object.defineProperty(obj, "x", { value: 10, writable: false });
obj.x = 20; // Throws an error

Conclusion

Applying `\“use strict\“` allows developers to create cleaner, safer, and more error-free JavaScript code by implementing better practices and preventing common errors earlier in the development cycle.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top