PUBLISHED JUNE 06, 2024
What is the Purpose of "use strict"?
Learn the purpose and benefits of using 'use strict' in JavaScript, including error prevention, improved security, and better coding practices with the goal to enhance code quality.
Prerequisite
Before diving in, you should have a basic understanding of the following concepts:
- ➢JavaScript Basics: Familiarity with basic syntax, variables, and functions.
- ➢JavaScript Scope: Understanding of global and local scope in JavaScript.
- ➢JavaScript Objects: Basic knowledge of how objects work, including properties and methods.
- ➢JavaScript Functions: Understanding how functions are declared and invoked.
- ➢Error Handling: Basic understanding of how JavaScript handles errors and exceptions.
Having these foundational concepts will help you grasp the importance and application of strict mode in JavaScript more effectively.
Overview of JavaScript
JavaScript is a versatile and widely-used programming language that powers the dynamic behavior of most websites.
It allows developers to create interactive web pages and is an essential part of web development, alongside HTML and CSS.
Initially developed to add interactivity to web pages, JavaScript has grown to become a full-fledged programming language used for both front-end and back-end development.
With the advent of frameworks and libraries such as React.js
, Node.j
s, and Angular
, JavaScript's popularity and capabilities have expanded significantly.
Introduction to "use strict"
Introduced in ECMAScript 5 (ES5), `use strict` is a directive that enables strict mode in JavaScript.
When strict mode is activated, it changes the way JavaScript code is executed, enforcing a stricter set of rules and reducing the chances of common programming errors.
By opting into strict mode, developers can write more secure and reliable code, as it helps catch errors early and prevents the use of certain problematic features of JavaScript.
The primary purpose of `use strict` is to ensure better coding practices and to make it easier to maintain and debug JavaScript code.
It achieves this by disallowing certain behaviors and syntax that can lead to bugs or make the code difficult to understand.
Overall, `use strict` helps developers adhere to modern JavaScript standards, leading to improved code quality and performance.
How to Enable Strict Mode
Enabling strict mode is straightforward. You simply add the string "use strict";
at the beginning of a script
or a function
. Here’s how you can enable it:
1. In a Script:
To apply strict mode to an entire script, place the directive at the top of your JavaScript file:
"use strict";
console.log("Strict mode is enabled for the entire script.");
// The rest of the code goes here
2.In a Function:
To apply strict mode to a specific function, place the directive at the beginning of the function body:
function fn() {
"use strict";
console.log("Strict mode is enabled for this function.");
// The rest of the function's logic goes here.
}
fn();
When strict mode is enabled, JavaScript executes the code with stricter parsing and error handling, which can help catch common coding mistakes and unsafe actions, leading to more robust and maintainable code.
1. Preventing the Use of Undeclared Variables
One of the most common issues in JavaScript is the use of undeclared variables, which can lead to unexpected behavior and hard-to-find bugs.
In non-strict mode
, assigning a value to an undeclared variable implicitly creates a global variable.
Strict mode eliminates this problem by throwing an error when an undeclared variable is used.
Example:
"use strict";
x = 10; // ReferenceError: x is not defined
2. Eliminating this
Coercion
In non-strict mode
, the value of this
inside functions that are not methods of an object defaults to the global object (window in browsers).
This behavior can lead to unexpected results, especially in the context of callbacks.
In strict mode, this
is undefined
in such cases, which helps avoid unintentional global variable creation.
Example:
"use strict";
function thisFn() {
console.log(this); // undefined
}
thisFn();
3. Disallowing Duplicates
Strict mode prevents the use of duplicate parameter names in function declarations, which can cause confusion and bugs in your code.
Example:
"use strict";
function sum(a, a, c) { // SyntaxError: Duplicate parameter name not allowed
return a + a + c;
}
console.log(sum(1,2,3)); // 7 in non strict mode instead of 6 🫣
7
instead of 6
. That alone is enough to make you always want to code in strict mode.
4. Catching Silent Errors
JavaScript sometimes fails silently without throwing errors, making it difficult to debug issues.
Strict mode transforms such `silent errors` into `throw errors`, making them easier to detect and fix.
Example:
"use strict"
var person = {};
Object.defineProperty(person, "name", { value: 'Yohan', writable: false });
person.name = "Lucky"; // TypeError: Cannot assign to read only property 'name'
console.log(person.name);
5. Preventing with
Statement
The with
statement is considered harmful because it changes the scope chain, making code harder to understand and optimize.
Strict mode disallows the use of the with
statement, leading to clearer and more predictable code.
Example:
"use strict";
with (Math) { // SyntaxError: Strict mode code may not include a with statement
x = round(2.3444);
console.log(x)
}
6. Securing JavaScript
Strict mode enhances the security of JavaScript by prohibiting certain actions that can make the code less secure.
For instance, it prevents the assignment to non-writable properties(as we saw above), prevents the usage of eval
in certain ways, and ensures that reserved words cannot be used as variable names.
Example:
"use strict";
var eval = 17; // SyntaxError: Unexpected eval or arguments in strict mode
const for = "is loop"; // SyntaxError: Unexpected token 'for' ('for' is not allowed as a variable declaration name.)
Differences Between Strict Mode and Non-Strict Mode
1. Error Handling
In non-strict mode, JavaScript sometimes fails silently without throwing errors, making it difficult to debug issues.
In contrast, strict mode transforms such silent errors into throw errors, making them easier to detect and fix.
2. Global Object Binding
In non-strict mode, when a function is called without a specified execution context (e.g., as a standalone function), this
inside the function refers to the global object (e.g., window
in browsers).
In strict mode, when a function is called without an execution context, this
is undefined
.
3. Variable Declaration
In non-strict mode, assigning a value to an undeclared variable implicitly creates a global variable.
In strict mode, attempting to assign a value to an undeclared variable throws a ReferenceError
.
4. Duplicates in Function Parameters and Object Literals
In non-strict mode, duplicate parameter names in function declarations is allowed.
In strict mode, using duplicate parameter names throws a SyntaxError
.
5. Octal Numeric Literals
In non-strict mode, octal numeric literals (e.g., 010
) are allowed, with a leading zero indicating octal notation.
In strict mode, octal numeric literals are disallowed, and attempting to use them results in a SyntaxError
. You can sort that out by change it to 0o10
(add an `o` after the leading 0
)
6. Arguments Object
In non-strict mode, modifying the arguments
object within a function affects the values of the corresponding named parameters.
In strict mode, modifying the arguments
object has no effect on the values of the named parameters.
function fn (x, y, z) {
console.log('Before Modification: ', arguments);
arguments[0] = 4;
console.log('Afetr Modification: ', arguments);
console.log('Params After Modif: ', x, y, z);
}
fn(1,2,3);
If you run the code above in strict mode, you will get :
Before Modification: [Arguments] { '0': 1, '1': 2, '2': 3 }
Afetr Modification: [Arguments] { '0': 4, '1': 2, '2': 3 }
Params After Modif: 1 2 3
No try running it in non strict mode, you will get :
Before Modification: [Arguments] { '0': 1, '1': 2, '2': 3 }
Afetr Modification: [Arguments] { '0': 4, '1': 2, '2': 3 }
Params After Modif: 4 2 3
7. with
Statement
The with
statement, which changes the scope chain, is allowed in non-strict mode but disallowed in strict mode.
Understanding these differences is crucial for writing JavaScript code that behaves consistently and predictably across different environments.
Recommended Practices
- ➢Enabling Strict Mode Globally: Consider enabling strict mode for your entire script to enforce strict rules and prevent common JavaScript pitfalls.
- ➢Using Strict Mode in Functions: When working with specific functions that require strict error handling or security measures, enable strict mode within those functions only.
Using Strict Mode in Functions vs. Global Scope
- ➢Function-Level Strict Mode: By enabling strict mode within individual functions, you can ensure that only the code within those functions is affected, allowing you to maintain backward compatibility with non-strict code in other parts of your application.
- ➢Global Strict Mode: Enabling strict mode globally affects the entire script, providing a more comprehensive approach to enforcing strict rules and preventing potential issues throughout your codebase.
Common Misconceptions
1. Strict Mode Slows Down JavaScript Execution
Misconception: Some developers believe that enabling strict mode negatively impacts JavaScript performance.
Reality: Strict mode does introduce additional checks and restrictions, but the impact on performance is negligible.
In fact, the optimizations and error checking provided by strict mode can often lead to more efficient code execution and better overall performance.
2.Strict Mode Is Only for New Projects
Misconception: There is a misconception that strict mode is only relevant for new projects and cannot be applied to existing codebases.
Reality: Strict mode can be applied incrementally to existing projects. You can enable strict mode for specific functions or modules without affecting the rest of your codebase, allowing you to gradually transition to stricter coding standards.
3. Strict Mode Makes JavaScript Syntax More Complex
Misconception: Some developers believe that strict mode introduces unnecessary complexity to JavaScript syntax, making code harder to write and maintain.
Reality: While strict mode does enforce stricter rules and disallows certain features, it ultimately leads to cleaner and more reliable code.
By catching errors early and promoting better coding practices, strict mode can actually simplify code maintenance and debugging in the long run.
4. Strict Mode Is Only Relevant for Web Development
Misconception: There is a misconception that strict mode is only relevant for web development and has limited applicability in other domains.
Reality: Strict mode is beneficial for any JavaScript project, regardless of its application domain. Whether you're building web applications, server-side applications with Node.js, or desktop applications with Electron, enabling strict mode can help improve code quality and maintainability.
5. Strict Mode Solves All JavaScript Errors
Misconception: Some developers believe that enabling strict mode will automatically fix all errors in their JavaScript code.
Reality: While strict mode helps catch common programming errors and enforce best practices, it cannot eliminate all possible errors.
You still need to write clean and well-structured code, use proper error-handling techniques, and conduct thorough testing to ensure the reliability of their applications.
Conclusion
`Use strict` is a powerful tool in JavaScript development that enables you to write cleaner, more reliable, and more secure code.
By opting into strict mode, you can enforce stricter rules, catch common errors early, and promote best coding practices.
Through features like preventing the use of undeclared variables, eliminating this
coercion, disallowing duplicates, catching silent errors, and more, strict mode helps you avoid common pitfalls and produce higher-quality code.
While strict mode may introduce some additional constraints, the benefits it provides in terms of code quality, maintainability, and security far outweigh any perceived drawbacks.
Whether you're working on a new project or maintaining an existing codebase, considering the adoption of strict mode can lead to more robust and efficient JavaScript applications.
By understanding the purpose, benefits, and best practices of `use strict`, you can leverage this feature to improve their coding workflows and create better software solutions.