Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Vance Zen
Vance Zen
2,854 Points

Is this valid: if ( 1 === 2 || placeholder) Assuming placeholder is a boolean value? i.e. placeholder = true ?

In the video, Dave says that there needs to be an expression on both sides of the '||' operator.

But can one side of the operator be a variable if that variable holds a boolean (true/false) value?

In other words are these if statements valid?

if ( 1 === 2 || placeholder)
if ( placeholder1 || placeholder)

assuming placeholder = true and placeholder 2 = false

Thanks !

Luke Bearden
Luke Bearden
15,597 Points

Yes, both of your if statement examples would be valid.

In your example if (placehoder1 || placeholder2) the || operator returns the value of placehoder1 if that value is truthy otherwise it returns placehoder2. Then the if statement evaluates the returned value for truthiness. Truthy values will return true and falsy values return false.

For more about logical operators: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators

Truthy values: https://developer.mozilla.org/en-US/docs/Glossary/Truthy

Falsy values: https://developer.mozilla.org/en-US/docs/Glossary/Falsy

2 Answers

Steven Parker
Steven Parker
228,991 Points

:point_right: Yes, that's perfectly fine, and commonly used in conditional statements.

Actually, the other side doesn't even need to be a boolean. If the left side evaluates to a false, the || operator returns whatever is on the right side. For example:

(1 === 2 || "hey")

...will return the string "hey", but you would probably not want to use that in a conditional! (It would actually evaluate as true, but it would be very confusing to read!)