How to Use Strict Mode in JavaScript to Achieve Desired Results?

Estimated read time 2 min read

In JavaScript, strict mode can help you achieve desired results by preventing certain unsafe actions and coding mistakes. Here are a few examples:

  1. Preventing variable declaration errors: Strict mode requires you to declare all variables with var, let, or const before using them. This helps prevent accidental global variable declaration.
"use strict";
x = 10; // Throws an error: x is not defined
let x = 10; // Correct
  1. Preventing property assignment to read-only properties: In strict mode, attempting to assign a value to a read-only property of an object will throw an error.
"use strict";
const obj = {};
Object.defineProperty(obj, "x", {value: 42, writable: false});
obj.x = 10; // Throws an error: Cannot assign to read only property 'x' of object '#<Object>'
  1. Preventing accidental deletion of variables: In strict mode, attempting to delete a variable or function will throw an error.
"use strict";
let x = 10;
delete x; // Throws an error: Deleting local variable in strict mode
  1. Preventing duplicated property names in an object literal: In strict mode, attempting to create an object literal with duplicate property names will throw an error.
"use strict";
let obj = {x: 10, x: 20}; // Throws an error: Duplicate data property in object literal not allowed in strict mode

By using strict mode, you can enforce a safer and more consistent coding style, and reduce the likelihood of introducing bugs and security vulnerabilities into your code.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply