In JavaScript, strict mode can help you achieve desired results by preventing certain unsafe actions and coding mistakes. Here are a few examples:
- Preventing variable declaration errors: Strict mode requires you to declare all variables with
var
,let
, orconst
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
- 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>'
- 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
- 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.
+ There are no comments
Add yours