Nullish Coalescing Operator (??)
Conditional (Ternary) Operator (?:) aka the Elvis Operator.
Optional chaining (?.)
The (??
) and (?:
) are both operators in JavaScript, but they serve different purposes.
Nullish Coalescing Operator (??
):
The “Nullish Coalescing” operator is a feature introduced in ECMAScript 2020 (ES11) JavaScript. It is represented by two question marks (??
) and is used to provide a default value for a variable if the variable is null
or undefined
, but not for other falsy values such as 0
, false
, or an empty string (""
).
The nullish coalescing (??
) 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.
- Introduced in ECMAScript 2020 (ES11).
- It provides a concise way to handle default values for variables that may be
null
orundefined
. - It returns the right-hand operand when the left-hand operand is
null
orundefined
; otherwise, it returns the left-hand operand.
let variable = null;
let result = variable ?? "default value";
console.log(result); // Output: "default value"
Conditional (Ternary) Operator (?:
):
- This is a standard JavaScript operator used for conditional expressions.
- It is a concise way of writing an
if-else
statement. - It evaluates a condition and returns one of two values depending on whether the condition is true or false.
- Not new 🙂 been in since its early versions of JavaScript.
let x = 5;
let result = x > 0 ? "positive" : "non-positive";
console.log(result); // Output: "positive"
TODO – Optional chaining (?.) more info.
In summary
- Use the Nullish Coalescing Operator (
??
) when you want to provide a default value for a variable if it isnull
orundefined
. - Use the Conditional (Ternary) Operator (
?:
) when you want to create a conditional expression based on a true/false condition.
These operators can be used in different scenarios, and choosing between them depends on the specific use case and the behaviour you want to achieve in your code.
MDN Docs
Nullish Coalescing
Conditional (Ternary)