28
loading...
This website collects cookies to deliver better user experience
??
). It takes a left-hand and right-hand operand, returning the right value if the left is null
or undefined
. Otherwise, it returns the left value.let x;
x = 1 ?? 100; // 1
x = null ?? 100; // 100
x = undefined ?? 100; // 100
x = 'Peas' ?? 'Carrots'; // Peas
x = null ?? 'Carrots'; // Carrots
x = undefined ?? 'Carrots'; // Carrots
Null
and undefined
, and not for false
and some other cases, like:let y;
y = -1 ?? 2; // -1
y = false ?? 2; // false
y = true ?? 2; // true
y = NaN ?? 2; // NaN
y = Infinity ?? 2; // Infinity
y = -Infinity ?? 2; // -Infinity
y = new Date() ?? 'soon'; // [the date object created by new Date()]
// use a ternary operator
const LetterIntro = ({name}) => {
return (
<div>
Hi {name ? name : 'there'},
</div>
)
};
const BetterLetterIntro = ({name}) => {
return (
<div>
Hi {name ?? 'there'}
</div>
)
}
??
operator is doing.??
to all your code.