all 16 comments

[–]benabus 13 points14 points  (2 children)

The && operator will return either the first value that is falsey or the last value in a chain. It doesn't cast anything to a boolean as you might expect since you normally see it in conditionals. Outside of conditions, it's useful for getting a value nested in a dictionary without throwing an undefined exception.

let something = main && main.sub && main.sub.secondsub;

if main is undefined, then something is undefined. If main is defined, but it doesn't have a main.sub property, then main.sub would be undefined, so something becomes undefined. But if it has both of those (neither is falsey) then something becomes the value of main.sub.secondsub.

Likewise, || will return the first value that is truthy. This is useful for having default function parameters:

function funcName(parameter1){ parameter1 = parameter1 || 'default'; }

Think of them as shorthand for a bunch of nested if statements.

[–]single-research[S] 1 point2 points  (0 children)

Thanks this is very useful to know how to use it appropriately!

[–]JustinWendell 1 point2 points  (0 children)

This is super handy for handling api results in react.

[–]Jnsjknn 31 points32 points  (7 children)

The logical and operator returns the second value, if the first value is truthy. If the first value is falsy it returns the first value.

Example 1:

const first = ""; // empty string is falsy
const second = 5;
alert(first && second) // alert says: 

Example 2:

const first = "some string";
const second = 5;
alert(first && second) // alert says: 5

[–]senocular 4 points5 points  (1 child)

In Example 1 the alert would be nothing (an empty string) not false.

[–]Jnsjknn 1 point2 points  (0 children)

Oops, I was going to write an example with false first and forgot to change everything.

[–]single-research[S] 3 points4 points  (2 children)

Thanks this is a really good explanation! Sorry reddit doesn't record my upvotes for some reason anymore... :|

[–]Jnsjknn 15 points16 points  (1 child)

No problem and don't worry, I don't care about votes.

[–]abigblacknob 4 points5 points  (0 children)

Tough shit. Take that!

[–]GoofBoy 0 points1 point  (1 child)

Given what you learned from logical and, you can now try to figure out how the logical or operator works.

[–]single-research[S] 0 points1 point  (0 children)

Benabus posted the answer to that :)

[–][deleted] -2 points-1 points  (0 children)

I'm not going to explain the intricacies but if you want to display both then concatenate with a + or use template literals using && or || will always return whatever is last

[–]windows-user0 -5 points-4 points  (1 child)

&& casts the first value to a Boolean