A notable addition in this ECMA proposal is the double question mark (??), commonly referred to as the Nullish coalescing operator. This operator functions as a logical operator that accepts two operands in JavaScript. It yields the right operand if the left operand is either null or undefined; otherwise, it returns the left operand.
The double question mark in JavaScript introduces a unique scenario involving the logical OR (||) operator. In this context, if the left operand evaluates to any falsy value—not exclusively null or undefined—the right operand is returned in the case of Nullish coalescing. It is important to note that the nullish coalescing operator carries the fifth-lowest precedence level among operators.
When to apply the nullish coalescing operator
In JavaScript, the nullish coalescing operator simplifies the management of null or undefined values. It allows developers to establish a reliable default value for such instances.
It can be helpful in the following circumstances when applied:
- Providing default values for potentially null or undefined variables: This feature eliminates the need to use the logical OR operator (||) in order to provide default values for variables that may be null or undefined. This can be useful, for example, if you want to avoid the unintended consequences of using the logical OR operator and the default value you provide is also a truth value.
- Managing optional function arguments: It has the ability to consistently and clearly handle optional function arguments. For example, consider that you have a function that takes optional arguments. You can then provide a default value for the argument using the nullish coalescing operator in case it is not supplied.
- Substitute the ternary operator: Nullish coalescing operator can be used to substitute the ternary operator (?:) in ternary expressions thereby simplifying them. This can facilitate reading and maintaining your code.
- Enhancing code readability: It offers a succinct and straightforward method of handling undefined or null values. It is generally utilized to make the code easier to read.
- Remember that in some circumstances, the logical OR operator should still be used instead of the nullish coalescing operator. The logical OR operator might still be required in some circumstances, such as when you need to set default values for truth values. So, it can be a helpful tool in circumstances where you specifically want to handle null or undefined values.
Syntax:
The operator that represents nullish coalescing is comprised of two question marks (??).
leftExpr ?? rightExpr
Result
- In the event that leftExpr is specified, then leftExpr,
- If leftExpr is unspecified, then rightExpr will be utilized.
Note: The point to be noted is ?? If the left argument is not undefined or null then it yields the left argument. Otherwise the right one is displayed.
How does it operate?
The expression located to the left of the double question mark (??) is evaluated as either undefined or null. In the event that it is indeed undefined or null, the expression yields the value to its right. Conversely, if it is not undefined or null, the expression returns the value on the left.
Suppose you are in the process of choosing a vehicle model. Upon visiting the primary website, you discover that the desired option is currently unavailable. Thankfully, you have an alternative model in mind that aligns with your preferences. In this context, the values displayed on the left signify the car, while those on the right indicate the specific model of the vehicle. You are in the midst of making a selection and are searching for the car when you encounter the double question mark (??).
let cars = null;
let Model = 'Kia';
let result = cars ?? Model;
console.log(result); // "Kia"
Output
JavaScript values that are regarded as false values
A value is designated as a false value (often denoted as false) when it is encountered within a Boolean context. The following six values in JavaScript are the sole ones considered to be false values.
false: The keyword false.
if (false) {
// Not reachable
console.log("It is not reachable"); // Program did not output anything!
}
Output
undefined: The primitive value.
if (undefined) {
// Not reachable
console.log("It is not reachable"); // Program did not output anything!
}
Output
null: The absence of any value.
if (null) {
// Not reachable
console.log("It is not reachable"); // Program did not output anything!
}
Output
""(empty string): Empty string value.
if ("") {
// Not reachable
console.log("It is not reachable "); // Program did not output anything!
}
Output
None of the preceding statements will produce any output since we have not specified any conditions within the "if" statement. Therefore, everything mentioned earlier signifies 'false values'.
Why was the Nullish Coalescing Operator necessary in JavaScript?
The || operator is quite beneficial. However, there are instances where we need to assess the subsequent expression solely when the first operand is either null or undefined.
The OR operator (||) serves the purpose of establishing a default value for a variable. Below is an illustrative example:
let value;
let example = value || 6 ;
console.log(example); // 6
Output
In the preceding example, the variable named value is not defined, which results in it being coerced to false. As a consequence, the result is 6.
Nonetheless, when you consider empty strings "" or the number 0 as acceptable values, the logical OR (||) operator may lead to some confusion, as illustrated in the following example:
let value = 0;
let result = value || 1;
console.log(result); // 1
Output:
The correct answer is 1, rather than 0, which may come as a surprise to you.
The nullish coalescing operator, represented by the double question mark in JavaScript, is employed to circumvent these issues. It exclusively yields the second value when the first value is either null or undefined.
In summary
To summarize, the double question mark feature in JavaScript is referred to as the nullish coalescing operator. This operator assigns a default value when dealing with null or undefined values and is represented by two consecutive question marks (??).
The nullish coalescing operator only yields the default value when the expression on the left evaluates to either null or undefined, differing from the logical OR operator (||). This allows for a more dependable and predictable way to manage null or undefined values in your programming without resorting to intricate conditional constructs. There are numerous scenarios in which the nullish coalescing operator proves beneficial, including assigning default values to variables, managing optional parameters in functions, and simplifying ternary expressions. By dealing with null or undefined values in a straightforward and clear manner, your code becomes more readable.
When it comes to managing null or undefined values within your code, the nullish coalescing operator serves as a beneficial enhancement to the JavaScript programming language overall.