JavaScript - use strict
What is "use strict"?
"use strict" is a directive in JavaScript that enforces a stricter parsing and error-handling mode for your code. It was introduced in ECMAScript 5 (ES5) to address some of the problematic features of JavaScript and to help developers write cleaner and more reliable code.
Example of "use strict":
"use strict";
function greet() {
message = "Hello, World!"; // Error: message is not defined
console.log(message);
}
greet();
In the above example, "use strict" mode will throw an error because the message is not declared with let, const, or var. Without "use strict", JavaScript would have implicitly created a global variable, which can lead to bugs.
How to Enable "use strict"
1. Strict Mode for the Entire Script
To enable strict mode for your entire JavaScript file, place "use strict" at the top of your script:
"use strict";
// Entire script is in strict mode
function sayHello() {
let name = "John";
console.log(`Hello, ${name}`);
}
2. Strict Mode for a Specific Function
You can also apply strict mode to individual functions:
function addNumbers(a, b) {
"use strict";
return a + b;
}
addNumbers(5, 10); // Works in strict mode
In this case, only the code inside the addNumbers function will be in strict mode.
Benefits of Using "use strict"
Enabling "use strict" provides several advantages, making your code more robust and secure. Here are some key benefits:
1. Prevents Accidental Global Variables
In non-strict mode, assigning a value to an undeclared variable automatically creates a global variable. "use strict" prevents this behavior by throwing an error.
"use strict";
x = 10; // Error: x is not defined
2. Catches Common Coding Mistakes
Strict mode catches common coding errors, such as assigning values to non-writable properties, using reserved keywords, or deleting variables/functions.
"use strict";
const obj = Object.freeze({ name: "Alice" });
obj.name = "Bob"; // Error: Cannot assign to read-only property
3. Disallows Duplicate Parameter Names
In non-strict mode, you can have duplicate parameter names, which can lead to unexpected behavior. Strict mode throws an error for duplicate parameter names.
function repeat(x, x) {
"use strict"; // Error: Duplicate parameter name not allowed
return x;
}
4. Prevents the Use of with Statements
The with statement is not allowed in strict mode because it makes code hard to predict and optimize.
"use strict";
with (Math) { // Error: 'with' statements are not allowed
console.log(sqrt(16));
}
5. Ensures Secure this Context
In strict mode, this remains undefined in functions that are not called as object methods, preventing accidental modifications to the global object.
"use strict";
function show() {
console.log(this); // Output: undefined
}
show();
Common Errors Caught by "use strict"
Strict mode catches several errors that would otherwise be silently ignored:
Error Type Non-Strict Mode Behavior Strict Mode Behavior
Undeclared variables Creates global variables Throws a ReferenceError
Assigning to a read-only property Fails silently Throws a TypeError
Deleting undeletable properties Fails silently Throws a TypeError
Duplicate function parameters Allowed Throws a SyntaxError
Octal numeric literals Allowed Throws a SyntaxError
Using with statement Allowed Throws a SyntaxError
this in global context References the global object undefined in functions
Differences Between Strict Mode and Non-Strict Mode
Here's a quick comparison of how code behaves in strict mode versus non-strict mode:
Example 1: Creating a Global Variable
// Non-Strict Mode
function globalVar() {
myVar = 20; // Implicitly creates a global variable
}
globalVar();
console.log(myVar); // Output: 20
// Strict Mode
"use strict";
function globalVarStrict() {
myVarStrict = 30; // Error: myVarStrict is not defined
}
globalVarStrict();
Example 2: Using this in Functions
// Non-Strict Mode
function showThis() {
console.log(this); // Output: Window object
}
showThis();
// Strict Mode
"use strict";
function showThisStrict() {
console.log(this); // Output: undefined
}
showThisStrict();
Best Practices for Using "use strict"
Always Use "use strict" in Your Code:
It's good practice to include "use strict" at the top of your scripts or functions for better code quality.
Avoid Mixing Strict and Non-Strict Code:
Consistently use strict mode across your project to avoid confusion.
Use Modern JavaScript Features:
ES6 modules and classes are in strict mode by default, so take advantage of modern syntax.
Test Thoroughly When Migrating to Strict Mode:
If you're adding "use strict" to existing code, test thoroughly to catch any new errors that may surface.
Conclusion
Using "use strict" in JavaScript is a simple yet powerful way to catch common errors, prevent potential security issues, and write cleaner code. It enforces stricter rules and helps you follow best practices, making your code more reliable and maintainable.