strict mode in JavaScript

"Strict mode" is a feature introduced in ECMAScript 5 (ES5) that allows you to write JavaScript code in a more disciplined and error-resistant manner. When you enable strict mode in your code, the JavaScript engine enforces a stricter set of rules and produces more helpful error messages, making it easier to catch common coding mistakes and avoid certain types of bugs. It helps to improve code quality, maintainability, and compatibility.

To enable strict mode, you simply add the following line at the top of a script or a function:

"use strict";

Here are the details of how strict mode works and its benefits, along with examples:

Benefits of Strict Mode

Error Prevention

Strict mode catches silent errors and throws exceptions for them. This helps in avoiding bugs that might otherwise be hard to diagnose.

Deprecated Features

Strict mode disables certain features that are considered error-prone or deprecated. This encourages using modern and reliable coding practices.

Variables

In strict mode, variables must be declared with var, let, or const. Undeclared variables will throw errors.

Global Object

In non-strict mode, assignments to undeclared variables create global variables. Strict mode prevents this behavior, reducing the risk of accidentally polluting the global namespace.

Assignment Restrictions

Strict mode disallows assignments to non-writable properties and properties of non-extensible objects.

Function Scope

In strict mode, functions have their own scope, and variables declared within functions are not accessible outside them.

Examples:
// Without strict mode (non-strict) function withoutStrictMode() { x = 10; // Assignment to an undeclared variable (creates a global variable) } withoutStrictMode(); console.log(x); // Outputs: 10 // With strict mode "use strict"; function withStrictMode() { y = 20; // Throws a ReferenceError: y is not defined } withStrictMode(); console.log(y); // Error: ReferenceError: y is not defined
// Without strict mode (non-strict) function sum(a, a, b) { return a + a + b; // Duplicate parameter names } console.log(sum(1, 2, 3)); // Outputs: 6 (no error) // With strict mode "use strict"; function strictSum(a, a, b) { return a + a + b; // Throws a SyntaxError: Duplicate parameter name not allowed in this context } console.log(strictSum(1, 2, 3)); // Error: SyntaxError: Duplicate parameter name not allowed in this context

Conclusion

Enabling strict mode is a good practice as it helps prevent common coding errors, encourages better programming habits, and promotes compatibility with modern JavaScript standards. It's important to note that strict mode does not affect the browser's built-in objects or the behavior of existing code; it primarily helps in writing new, more reliable code.