JavaScript "use strict"
🚀
What is "use strict"
?
"use strict"
is a directive in JavaScript that enforces a stricter set of rules to help catch common mistakes and unsafe actions. It prevents the use of bad syntax and improves performance by making JavaScript code more predictable.
1️⃣ How to Enable "use strict"
🔹 At the Beginning of a Script (Global Strict Mode)
✔ If "use strict"
is declared at the top of the script, the entire script runs in strict mode.
🔹 Inside a Function (Local Strict Mode)
You can also apply "use strict"
inside a function, instead of globally.
✔ This ensures strict mode is only applied within the function, leaving the rest of the script unaffected.
2️⃣ Benefits of "use strict"
✅ Prevents accidental global variables
✅ Throws errors for unsafe actions
✅ Makes debugging easier
✅ Prepares code for future JavaScript versions
✅ Improves performance in some cases
3️⃣ Errors Caught by "use strict"
🔹 1. Prevents Accidental Global Variables
Without "use strict"
, JavaScript automatically creates global variables, which can lead to unexpected bugs.
🔹 2. Prevents Duplicating Parameter Names
✔ In non-strict mode, this is allowed, but it can cause confusion.
🔹 3. Restricts this
in Functions
In non-strict mode, this
in a function defaults to the global object (window
in browsers). Strict mode sets this
to undefined
.
✔ This helps prevent unintended modifications of the global object.
🔹 4. Prevents Deleting Non-Deletable Properties
✔ In non-strict mode, the delete
statement fails silently, but in strict mode, it throws an error.
🔹 5. Prevents Assigning to Read-Only Properties
🔹 6. Prevents Using with
Statement
✔ The with
statement makes code harder to predict, so it's disallowed in strict mode.
4️⃣ Does "use strict"
Apply to ES6 Modules?
Yes! All ES6 modules (import
/ export
) automatically use strict mode, even if you don’t write "use strict"
.
🎯 Summary
🔹 "use strict"
helps catch common JavaScript mistakes
🔹 Prevents accidental global variables
🔹 Throws errors for bad syntax
🔹 Restricts unsafe operations
🔹 Improves performance in some cases
Should you use "use strict"
? ✅ Yes! It helps write cleaner, safer JavaScript code. 🚀
💡 Need more details? Let me know! 😊