Why Strict Mode is a Must-Have for Your JavaScript Development: Explained with Code Examples
JavaScript has two modes of execution: strict mode and sloppy mode. Strict mode was introduced in ECMAScript 5 and it helps developers to write safer and more efficient code. In this article, we will take a look at the most important features of strict mode and how it can help us to avoid common mistakes.
First, it is important to note that strict mode is an opt-in feature, meaning that developers must explicitly enable it in their code. This allows developers to choose whether or not to use strict mode on a per-script or per-function basis. To enable strict mode, simply add the string 'use strict' at the beginning of your script or function.
1. Fix the accidental creation of global variables
In strict mode, we cannot assign a value to an undeclared variable. This is a common mistake that can lead to unexpected behavior and bugs in our code. For example, in the following code, we are trying to assign a value to the variable nme which was not declared before, this will throw an error in strict mode.
let name = 'Ernesto'
let age = 36;
if (age > 20) {
nme = 'Pepe'; // We cannot assign a value to an undeclared variable
};
2. Read only properties
In strict mode we cannot assign a new value to a read only property. This means that we cannot change the value of an object's property if it is defined as read-only. For example, in the following code, we are trying to change the value of the 'name' property of the user object, which is defined as read-only. This will throw an error in strict mode.
const user = {}
Object.defineProperty(user, 'name', {value: 'Ernesto', writable: false});
user.name = 'Pepe'; // We cannot assign a new value to a read only property;
console.log(user.name);
3. No extensible objects
In strict mode we cannot add a property to an object if it is defined as not extensible. This means that we cannot add new properties to an object if it is defined as not extensible. For example, in the following code, we are trying to add the property 'age' to the user object, which is defined as not extensible. This again will throw an error in strict mode.
const user = {name: 'Ernesto'}
Object.preventExtensions(user);
user.age = 36; // We cannot add the property age, because the object is defined as not extensible.
console.log(user);
4. Duplicated parameters
In strict mode we cannot duplicate parameters of a function. This means that we cannot have two or more parameters with the same name in a function. For example, in the following code, we are trying to define a function with two parameters with the same name, in strict mode this won't work and will throw an error.
// In strict mode we cannot duplicate parameters of a function
function sayHello(name, lastName, name)
console.log(`Hello ${name} ${lastName}`);
}
sayHello('Ernesto', 'Roca');
5. Octal numeral system
With the octal numeral system (base 8) we can represent any number with digits from 0 to 7. It is often used to represent file permissions, such as in the Unix file system and the C programming language. In some cases, octal is used to represent colors in web development, as it allows for more compact representation of colors using a three-digit code. In strict mode the correct way to use octal numeral system is with an o lowercase or O uppercase after the zero 0, e.g: 0o11, 0o23.
// In strict mode this is a SyntaxError
console.log(011); // In console: 9 (1 + (1 * 8));
console.log(023); // In console: 19 (3 + (2 * 8));
// The correct way to write this is using a o lowercase or O uppercase after the zero 0
console.log(0o11);
console.log(0o23);
6. Delete
The operator delete helps to delete properties of an object or elements in an array returning true or false if it was deleted or not. We cannot delete a variable, a function or the object window, returning false. In strict mode the operator delete applied to these elements throw a SyntaxError.
function sayHello() {
console.log('Hello');
}
const myName = 'Ernesto';
// In strict mode delete for this elements throw a SyntaxError
delete myName; // false in sloppy mode
delete sayHello; // false in sloppy mode
delete window; // false in sloppy mode
7. Arguments and eval are keywords
In strict mode arguments and eval are keywords, if we use them as variable names in our code, it will throw an error.
// let eval = 'a'; // SyntaxError in strict mod
// let arguments = 'b'; // SyntaxError in strict modee
8. With is not allowed
The instruction "with" extends the scope chain in JavaScript temporarily. In strict mode code may not include a "with" statement.
// With the instruction of with
// Instead to do this:
document.forms[0].email.value = '';
document.forms[0].pasword.value = '';
// We do this (not allowed in strict mode):
with (document.forms[0]) {
email.vale = '';
password.value = '';
}
The statement "with" slows down the reading process of JavaScript's engine. We can better store a reference of the object in a variable. Like this:
const form = document.form[0];
form.email.value = '';
form.password.value = '';
9. New reserved word
In strict mode there are more reserved words, e.g. implements, package, public, interface, static, private, protected, yield, let.
10. The behavior of free functions
In strict mode, the object "window" is not the owner of free functions, meaning that if a function is assigned to a variable and then invoked, the "this" keyword inside the function will not reference the "window" object. Instead, it will be undefined. This can lead to errors if the function relies on the "this" keyword to access properties or methods. In this example, the function "sayHello" is a method of the object "user", which references the "name" property of the object. When the function is assigned to a variable "sayHello" and invoked, the "this" keyword inside the function no longer references the "user" object and instead is undefined. This results in an error when trying to access the "name" property which is "Cannot read properties of undefined (reading 'name')", a very common but useful error in JavaScript.
const user = {
name: 'Ernesto',
sayHello: function () {
console.log(`Hello, I am ${this.name}`);
}
}
// user.sayHello(); // In console: Hello, I am Ernesto
const sayHello = user.sayHello;
sayHello(); // In console: Hello, I am undefined. In strict mode it will throw a TypeError: Cannot read properties of undefined (reading 'name')
Strict mode is a powerful tool that helps developers to write safer and more robust code by enforcing a set of rules that prevent common coding mistakes. By using strict mode, developers can avoid accidentally creating global variables, modifying read-only properties, extending non-extensible objects, and more. Additionally, strict mode disallows certain features that are considered harmful or confusing, such as the with statement and the octal numeral system.
However, strict mode is not a silver bullet and it's important to keep in mind that it might also break some code that works in sloppy mode. Therefore, it is recommended to use strict mode in development and test it thoroughly before deploying it to production.
Thanks for reading.