Using && to set a Logical Value

While the double pipe || (logical OR) is useful to set a default value, a double && will set an alternate value. Below is a comparison of the difference:

%MINIFYHTMLf6a0560b7e7f697c026c41776cb5f53023%let name = ''
name || 'Brian'Code language: JavaScript (javascript)

name is now set to ‘Brian’ as the value was null, so the || set ‘Brian’ as the default instead.

let name = 'Brian'
name === 'Brian' && 'JimCode language: JavaScript (javascript)

In the second example, the alternate will be picked, if the condition is true. name is ‘Brian’ so we swap that value out for ‘Jim’.

let name = ''
name === 'Jerry' && 'Jim'Code language: JavaScript (javascript)

In the above, the name value would be false.

About Author /

Leave a Comment

Your email address will not be published.

Start typing and press Enter to search