Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
216,164 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!)