Close

2023-11-03

The ? and ?? operators, In JavaScript

The ? and ?? operators, In JavaScript

In JavaScript, the ? and ?? operators are used for conditional and nullish coalescing operations, respectively. Let’s delve into each:

  1. ? (Ternary Operator):
    The ? operator is part of the ternary conditional operator, a shorthand for a if-else statement. It’s used as condition ? valueIfTrue : valueIfFalse. Example:
   let age = 18;
   let status = (age >= 18) ? 'adult' : 'minor';
   console.log(status); // Outputs: "adult"

In the example above, if the age is 18 or more, the status will be set to ‘adult’. Otherwise, it will be set to ‘minor’.

  1. ?? (Nullish Coalescing Operator):
    The ?? operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. Example:
   let value = null;
   let defaultValue = "Default";
   let result = value ?? defaultValue;
   console.log(result); // Outputs: "Default"

In the example above, since value is null, the result will be set to the value of defaultValue, which is “Default”.

It’s important to note that the nullish coalescing operator (??) is distinct from the logical OR (||) operator. While || returns the right-hand operand when the left-hand operand is falsy (which includes 0, '', false, null, undefined, and NaN), ?? only considers null and undefined.