And and or operators

how the following works

alert( 5 || 1 && 0 );


let x = 1;

(x > 0) && alert( ‘Greater than zero!’ );

It starts from the last operator and works its way to the left.

With alert( 5 || 1 && 0 ) it compares 1 && 0 giving a truthy or falsy value, then with 5 || ... to give a truthy or falsy value.

&& operator

The AND operator && checks if the value to the left is truthy or falsy. If the left value is falsy, it doesn’t check what’s to the right and returns that left value. If it’s truthy, it returns the right value.

That reduces what’s in brackets down to (5 || 0)

|| operator

How the OR operator || works, is that is gives the first value that is truthy. With 5 || 0 the 5 is truthy, so that’s the value that it gives, resulting in a reduction down to (5)

Guard clause

You’ll also see the && operator used as a guard clause. Only if the stuff to the left is truthy, does it allow execution of what’s on the right.

You have an example of that in the above code.

Default value

The || operator is also used to give a default value, so that if a value is falsy, you can use the || operator to assign a default value to it instead.

An example of that is:

var zoomFactor = opts.zoomFactor || 1;
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.