&& (double ampersand) and
|| (double pipes) to denote
or respectively. Think of it is a symbolic representation of the English words.
However, we can use both of these symbols to determine if something is truthy. This can also help with variable assignment if we’re relying upon other variables having values.
Let’s see if you can follow the logic with these examples.
If you are testing whether a variable is truthy and want to return another truthy value you can do the following:
var e = “test”; var f = 2; console.log( e && f ); // as both variables are true returns the last variable `f` being 2.
If we changed the value of
e to a falsey value such as
0, we get…
var e = null; var f = 2; console.log( e && f ); // => null
If we switch it, such that
f is a falsey value we get…
var e = 2; var f = 0; console.log( e && f ); // => 0
So in both of the previous two cases the falsey value gets returned.
What happens then if we replace the
||, here are our results:
var e = "test"; var f = 2; console.log( e || f ); // => "test"
Notice how we get the first truthy value.
var e = null; var f = 2; console.log( e || f ); // => 2
And again we get the first truthy value being the variable
So what would you expect if we now started combining these expressions?
var e = null; var f = 2; console.log( e && f || 1 ); => 1
( e && f ) expression returns the first falsey value, being
null it’s then used in the second comparative statement
null || 1 and we know that with
|| comparisons it returns the first truthy value being
1 (as null is falsey).