Master JavaScript Strict Mode: Benefits, Common Pitfalls, and How to Use It
This guide explains JavaScript’s Strict Mode—how to enable it with "use strict", why it improves code safety and engine optimization, and highlights common traps such as undeclared variables, deleting identifiers, duplicate parameters, octal literals, with statements, and incorrect this binding, offering correct practices for each.
JavaScript’s Strict Mode, introduced in ECMAScript 5, makes code execution safer and helps avoid common programming errors. By adding the directive "use strict" at the beginning of a script or function, the mode is activated.
Why Use Strict Mode?
Strict Mode converts many silent errors in ordinary JavaScript into thrown errors, helping developers write more robust code. It also fixes certain flaws that hinder JavaScript engine optimizations.
How to Enable Strict Mode
// Global enable
"use strict";
// Or enable inside a function
function myFunction() {
"use strict";
// function code
}Common Pitfalls in Strict Mode
1. Undeclared Variables
In non‑strict mode, assigning a value to an undeclared variable creates a global variable automatically. In Strict Mode, this throws an error.
"use strict";
x = 10; // Error: x is not definedCorrect practice: Always declare variables with var, let, or const.
2. Deleting Variables or Functions
"use strict";
var x = 10;
delete x; // Error: cannot delete a variable
function test() {}
delete test; // Error: cannot delete a functionCorrect practice: Do not attempt to delete variables or functions.
3. Duplicate Parameter Names
Correct practice: Ensure that function parameter names are unique.
4. Octal Syntax
"use strict";
var num = 010; // Error: invalid octal syntaxCorrect practice: Use the 0o prefix for octal literals.
var num = 0o10; // Valid octal representation5. with Statement
Correct practice: Specify the object explicitly instead of using with.
6. Assigning to Read‑Only Properties
Attempting to assign values to read‑only properties throws an error in Strict Mode.
7. this Value
In Strict Mode, the this keyword inside a function does not default to the global object.
"use strict";
function showThis() {
console.log(this); // undefined, not the global object
}
showThis();Avoid these pitfalls to make your code more robust and to develop better programming habits.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JavaScript
Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
