Operators Flashcards
What is returned from:
false || ‘’ || true
‘’ || false || 0
How might this be used?
true
0
alert( firstName || lastName || nickName || “Anonymous”);
Alerts the name if a name is there, otherwise alerts “Anonymous”
OR
true || alert(“not printed”);
false || alert(“printed”);
Alerts depending if the printed-condition is true.
What is returned from:
true && 0 && true
‘1’ && ‘2’ && ‘3’
0
‘3’
Does && or || have higher precedence
&& has higher precedence
What happens with:
console.log(( console.log(1) || console.log(2) || console.log(3) ));
1
2
3
undefined
The expressions in && and || are run even if they are not returned.
What happens with:
console.log(( console.log(1)));
1
undefined
What happens with
alert( alert(1) && alert(2) );
1 (alert(1) returns undefined, so the comparison stops and alert(1) is evaluated)
undefined
Will this alert true?
alert( null || 2 && 3 || 4 );
No
It will alert 3.
within an if statement or ? operator, it will evaluate true or false. But does not on it’s own.
Do || and && return Boolean?
no
What is ?? called?
what’s does it do?
Nullish coalescing operator ‘??’
Returns the first non-null and non-undefined operand.
Or returns the last processed value
What’s returned from
false ?? true
false ?? null
null ?? false
false
false
false
What is the main use case for Nullish coalescing operator ‘??’ ?
The common use case for ?? is to provide a default value for a potentially undefined variable.
alert(user ?? “Anonymous”);
|| will also skip false and other falsey things. ?? only skips null and undefined
Difference between || and ??
|| returns the first truthy value.
?? returns the first defined value. It doesn’t treat 0, ‘’, or false as undefined.
|| doesn’t distinguish between false, 0, an empty string “” and null/undefined.
What is alerted
let height = 0;
alert(height || 100);
alert(height ?? 100);
// 100 // 0
Put brackets around the precedence let area = height ?? 100 * width ?? 50;
let area = (height) ?? (100 * width) ?? (50);
When in doubt (about effect or readability), use parenthesis
What happens with:
let x = 3;
console.log( (x = 2) && 7 );
console.log(x);
7
2
The expressions in && and || are run even if they are not returned.