Strict mode in JavaScript programming

Strict mode in JavaScript

 Strict mode in JavaScript is a way to enforce stricter rules and restrictions when writing JavaScript code, which can help identify and prevent potential errors, security leaks, or performance issues. It is enabled by adding the following line at the beginning of a script or a function:

"use strict";
When strict mode is enabled, the JavaScript interpreter will throw errors or disallow certain actions that are allowed in non-strict mode. Some examples of changes in strict mode include: 1. Variables must be declared with var, let, or const before being used, otherwise an error is thrown. Non-strict mode:
x = 10; // No error, even though 'x' is not declared console.log(x); // 10
Strict mode:
"use strict"; x = 10; // Error: x is not defined console.log(x);
2. Assigning a value to an undeclared variable, read-only property, or non-writable global variable will throw an error. Non-strict mode:
NaN = "not a number"; // No error, even though NaN is read-only console.log(NaN); // "not a number"
Strict mode:
"use strict"; NaN = "not a number"; // Error: Assignment to constant variable console.log(NaN);
3. Octal literals (numbers with a leading zero) are not allowed in strict mode. Non-strict mode:
var num = 010; // No error, 'num' is treated as an octal number (8 in decimal) console.log(num); // 8
Strict mode:
"use strict"; var num = 010; // Error: Octal literals are not allowed in strict mode console.log(num);
These are just a few examples of the differences between strict and non-strict mode in JavaScript. Using strict mode can help catch potential issues in your code early, making it easier to write more robust and maintainable code.

Comments

Popular posts from this blog

Whiteboarding Interviews

Version Control with Git: A Beginner’s Guide

Callback function in JavaScript