Just Learn Code

Simplify Your Code with the Elvis Operator in JavaScript

Introduction to the Elvis Operator

Have you ever come across a null or undefined value in your JavaScript code that caused you a headache? Or perhaps, you wanted to set a default value for a variable but found it tedious to write an if statement?

The Elvis Operator might be the solution you need!

What is the Elvis Operator? The Elvis Operator, also known as the ternary operator or nullish coalescing operator, is a shorthand notation used in JavaScript to assign a default value to a variable if it is null or undefined.

The operator is represented by two question marks (??), and it is a syntax sugar for an if statement.

Use of Elvis Operator in JavaScript

The Elvis Operator is used when you want to assign a default value to a variable that might be null or undefined. In such cases, instead of using an if statement to check if the variable is null or undefined, then assign the default value, you can use the Elvis Operator to achieve the same result with less code.

For instance, imagine you have an object with a property called “name,” and you want to assign its value to a variable called “val.” However, the “name” property might be null or undefined, and you don’t want to assign those values to your variable. Instead, you want to assign a default value in case the “name” property is null or undefined.

Before the introduction of the Elvis Operator, the conventional way of doing this was through an if statement like this:

if (object.name !== null && object.name !== undefined) {

val = object.name;

} else {

val = “default value”;

}

This if statement checks if the “name” property of the object is not null or undefined. If it is not null or undefined, the value is assigned to the “val” variable.

Otherwise, the default value is assigned to the “val” variable. However, with the Elvis Operator, you can achieve the same result with fewer lines of code like this:

val = object.name ??

“default value”;

The ?? operator checks if the “name” property is null or undefined.

If it is either null or undefined, the “default value” is assigned to the “val” variable. Otherwise, the value of the “name” property is assigned to the “val” variable.

Implementation of Elvis Operator in JavaScript

Syntax of Elvis Operator

The syntax of the Elvis Operator is simple. It checks if the left-hand side of the operator is null or undefined.

If it is not null or undefined, it returns the left-hand side, else it returns the right-hand side of the operator. The syntax of the Elvis Operator is:

leftExpr ??

rightExpr

Where leftExpr is the expression whose value is checked for null or undefined, and rightExpr is the default value that is assigned to the variable if leftExpr is either null or undefined.

Condition for using Elvis Operator

The Elvis Operator is used when you want to assign a default value to a variable that might be null or undefined. If the variable is not null or undefined, its value is returned, else, the default value is assigned to it.

Example code with Elvis Operator

Let us demonstrate the implementation of the Elvis Operator with an example. Consider the following object:

const myObject = {

name: “John”,

age: 20,

height: 1.75,

weight: null

};

The “myObject” object has a “weight” property that is null.

We want to assign the value of the “weight” property to a variable called “myWeight.” However, since the “weight” property might be null, we want to assign a default value of 0 if it is null. We can achieve this with the Elvis Operator like this:

const myWeight = myObject.weight ??

0;

The Elvis Operator checks if the “weight” property of the “myObject” object is null or undefined. If it is null, the value 0 is assigned to the “myWeight” variable.

Otherwise, the value of the “weight” property is assigned to the “myWeight” variable.

Conclusion

In conclusion, the Elvis Operator is a shorthand notation that simplifies the assignment of default values to variables that might be null or undefined. It eliminates the need for an if statement when assigning default values.

The operator is represented by two question marks (??), and it returns the left-hand side of the operator if it is not null or undefined, else it returns the right-hand side of the operator. The Elvis Operator is a simple and effective way of writing concise and readable code in JavaScript.

3) Complex Example with Multiple Expressions

So far, we have seen how the Elvis Operator simplifies the assignment of default values to single expressions. But what if we have multiple expressions that need to be checked, and a default value needs to be assigned if all of them are null or undefined?

Let’s dive into a more complex example using the Elvis Operator.

Use of Elvis Operator with Multiple Expressions

Consider the following object:

const myObject = {

id: 123,

name: null,

email: undefined,

phone: “(555)555-5555”

};

We want to check the “name,” “email,” and “phone” properties of the “myObject” object and assign a default value if they are all null or undefined. We can achieve this with a single statement using the Elvis Operator like this:

const myContact = myObject.name ??

myObject.email ?? myObject.phone ??

“No contact information available”;

In this example, we are checking the “name,” “email,” and “phone” properties of the “myObject” object using the Elvis Operator. The first expression that is not null or undefined is returned, starting with the leftmost expression.

If all the expressions are null or undefined, the default value “No contact information available” is assigned to the “myContact” variable.

Condition for returning default value

The primary condition for returning a default value with multiple expressions is that all the expressions must be null or undefined. The Elvis Operator checks for the values of the expressions from left to right until it finds the first expression that is not null or undefined.

Output with multiple expressions

In our example, the output of the “myContact” variable with the multiple expressions is:

“No contact information available”

since all the expressions are null or undefined.

4) Comparison with Logical OR Operator

The logical OR operator (||) can also be used to assign default values. However, it has some issues that can lead to unexpected behavior when working with Booleans or invalid values.

Issues with Logical OR Operator

Consider this example using the logical OR operator:

const name = myObject.name || “default name”;

The logical OR operator checks if the “name” property of “myObject” is a truthy value. If it is not a truthy value, the default value “default name” is assigned to the “name” variable.

However, if the “name” property is an empty string (“”) or a value that evaluates to false such as 0 or NaN, the default value will be assigned instead of the intended value.

Comparison with Elvis Operator

The Elvis Operator avoids these issues by checking explicitly for null or undefined values. The logical OR operator executes the right-hand side of the operator when the left-hand side is a falsy value, which can lead to unexpected results.

In contrast, the Elvis Operator returns the default value only when the left-hand side of the operator is null or undefined.

Output comparison between OR and Elvis operator

Consider this example with the logical OR operator and the Elvis Operator:

const messageOrElvis = “hello” || false; // Result: “hello”

const messageElvis = “hello” ?? false; // Result: “hello”

Here, we are checking if the “message” variable is a truthy value, and if not, assigning a default value of false using the logical OR operator and the Elvis Operator.

In the first case with the logical OR operator, the default value “false” is not assigned since “hello” is a truthy value. In the second case with the Elvis Operator, the default value “false” is not assigned either since “hello” is not null or undefined.

Conclusion

In conclusion, the Elvis Operator is a powerful shorthand operator that simplifies the assignment of default values in JavaScript. It is especially useful when dealing with null or undefined values and multiple expressions.

The Elvis Operator is more reliable and predictable than the logical OR operator, which can lead to unexpected behavior when working with Booleans or invalid values. By understanding the correct usage of the Elvis Operator in different scenarios, you can write more efficient and concise code while reducing the potential for errors.

5)

Conclusion

In today’s world, where efficiency is the key to success, any programming language should strive to provide concise and simple solutions to complex problems. JavaScript, being one of the most popular programming languages, understands this very well, which is why it offers several shorthand operators to simplify code.

The Elvis Operator, also known as the nullish coalescing operator, is one such operator that significantly impacts the way we write JavaScript code.

Importance of Elvis Operator in JavaScript

The Elvis Operator has become an essential tool for developers in reducing the amount of code needed to assign default values in their JavaScript applications. It has proven to be a time-saver, especially considering the fact that conditions for null and undefined values occur quite often in applications.

The Elvis Operator simplifies the process of assigning default values and helps in producing more efficient code. This operator significantly reduces the dependency on using the traditional ‘if’ statements that can often bloat the codebase.

Furthermore, with the introduction of optional chaining in ES2020, the Elvis Operator has become even more powerful. Optional chaining allows developers to use the Elvis Operator to access nested properties of an object and assign default values to every level of the object.

By combining these two operators, developers can write concise and readable code even for complex nested objects. Additionally, the Elvis Operator can be used in combination with other operators, like the ternary operator, to achieve more complex behavior in a single statement.

This flexibility and simplicity make the Elvis Operator a versatile tool in JavaScript programming. In conclusion, the Elvis Operator is an essential shorthand operator in the JavaScript language that greatly simplifies code when assigning default values.

Developers can use this operator to produce efficient and concise code that performs the same function as extensive ‘if’ statements. With the release of optional chaining, developers can take advantage of the Elvis Operator to access deeply nested objects.

The Elvis Operator not only saves time and reduces bloated code but also makes code more readable and easier to write. Understanding the proper usage of this operator can result in more efficient and succinct code, ultimately improving the performance of JavaScript applications.

The Elvis Operator, also known as the nullish coalescing operator, is a powerful shorthand syntax in JavaScript that assigns default values to null and undefined values. Its primary use is providing a concise and efficient way of writing code, reducing bloated ‘if’ statements.

The Elvis Operator is versatile in its application, from single expressions to complex nested objects, making it a reliable tool for developers. By using this operator, developers can make their code more efficient, readable, and reliable.

The Elvis Operator is an essential part of the JavaScript development toolkit, making it an essential syntax to master for anyone interested in improving their development skills.

Popular Posts