Home » Strict Mode in JavaScript

Strict Mode in JavaScript

Strict Mode in JavaScript

Let’s dive into strict mode in JavaScript with code examples, illustrating the key concepts and highlighting what is allowed and what isn’t under strict mode.

Enabling Strict Mode in JavaScript

"use strict";
console.log("Strict mode is enabled.");
JavaScript

Allowed Enhancements and Enforced Restrictions

1. Preventing Accidental Globals

Without strict mode, assigning a value to an undeclared variable creates a global variable, which can lead to bugs. Strict mode disallows this.

Non-strict mode (problematic):

function myFunc() {
  accidentalGlobal = "This is bad!";
}
myFunc();
console.log(accidentalGlobal); // "This is bad!"
JavaScript

Strict mode (safe):

"use strict";
function myFunc() {
  accidentalGlobal = "This is not allowed!"; // ReferenceError: accidentalGlobal is not defined
}
JavaScript

2. Immutable Properties and Read-only Restrictions

Strict mode throws errors when trying to modify read-only properties or deleting undeletable properties.

Attempt to modify a read-only property:

"use strict";
var obj = {};
Object.defineProperty(obj, "readOnly", {
  value: "This cannot change",
  writable: false
});
obj.readOnly = "Try changing me"; // TypeError: Cannot assign to read-only property

JavaScript

3. Disallowing Duplicates in Object Literals and Function Parameters

Strict mode ensures object literals and function parameters are unique, preventing confusing bugs.

Duplicate property names:

"use strict";
var obj = {
  prop: 1,
  prop: 2 // SyntaxError: Duplicate data property in object literal not allowed in strict mode
};
JavaScript

Duplicate parameter names:

"use strict";
function duplicateParams(a, a) { // SyntaxError: Duplicate parameter name not allowed in strict mode
  return a;
}
JavaScript

4. Octal Syntax and with Statement Restrictions

Strict mode forbids octal syntax and the use of the with statement, both of which can lead to ambiguous code.

Octal syntax:

"use strict";
var num = 0o10; // Octal syntax is allowed using the 0o or 0O prefix
var num = 010; // SyntaxError: Octal literals are not allowed in strict mode.
JavaScript

with statement:

"use strict";
var obj = { a: 1, b: 2 };
with (obj) { // SyntaxError: Strict mode code may not include a with statement
  console.log(a + b);
}
JavaScript

5. Eval and Primitive Property Assignments

Strict mode creates a safer environment when using eval and prevents setting properties on primitives.

eval creating variables:

"use strict";
eval("var createdInEval = true;");
console.log(createdInEval); // ReferenceError: createdInEval is not defined
JavaScript

Setting properties on primitives:

"use strict";
var num = 1;
num.prop = "Property"; // TypeError: Cannot create property 'prop' on number '1'
JavaScript

6. Access to arguments.callee and arguments.caller

Strict mode restricts access to arguments.callee and arguments.caller for cleaner, more optimizable code.

"use strict";
function exampleFunc() {
  var caller = arguments.callee.caller; // TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed
}
JavaScript

Conclusion

Strict mode in JavaScript enforces a cleaner, safer coding environment by imposing restrictions that prevent common errors, such as creating global variables by mistake, modifying immutable properties, or using deprecated and potentially confusing syntax. Understanding and applying strict mode in your JavaScript projects enhances code quality, security, and maintainability.

Frequently Asked Questions

Q1. What is strict mode in JavaScript?

Ans: Strict mode is a way to opt in to a restricted variant of JavaScript, thereby implicitly opting-out of “sloppy mode”. It eliminates some JavaScript silent errors by changing them to throw errors, fixes mistakes that make it difficult for JavaScript engines to perform optimizations, and prohibits certain syntax likely to be defined in future versions of ECMAScript.


Q2. How do you enable strict mode?

Ans: Add "use strict"; at the beginning of a script or function to enable strict mode.


Q3. Can strict mode be applied to specific functions?

Ans: Yes, it can be applied to individual functions by placing "use strict"; at the beginning of the function body.


Q4. What are key restrictions of strict mode?

Ans: Prevents accidental global variables.
Throws errors for assignments to non-writable properties and for attempting to delete undeletable properties.
Disallows duplicate parameter names and object literal properties.
Forbids octal syntax and the with statement.
Limits eval usage and setting properties on primitives.


Q5. Why does strict mode throw errors for normally silent failures?

Ans: To make JavaScript coding safer and more error-proof, ensuring developers catch and fix issues during development.