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

JavaScript Foundations - Objects - Call and Apply

Hi, I have a quick question regarding the or operator ( || ) with regards to JavaScript in conjunction with this video. Here is the relevant code,

greet: function (name, mood) {
name = name || "You";
mood = mood || "good";

etc
}

I was under the impression that the || operator returns a boolean value (true or false) when used, I come from a Java background so maybe I am confusing something here. In this instance it seems as though Jim is checking to see whether 'name' has a value (is true) and if it is not then "You" is substituted in, but this seems more like a conditional operation (using ? syntax). Can anyone clarify?

After some Google work I see that the first expression is returned should it be converted to 'true' else the second expression is returned. Just wanted to say this is not clarified or discussed anywhere in the 'Front-end Web Development Track' up to JavaScript Foundations. Would've been useful to know earlier.

J Scott Erickson
J Scott Erickson
11,883 Points

Its actually a pretty common programming trick. with the "or" operator "||" if the first statement succeeds then the second never needs to evaluate. However if the first condition fails then second evaluates. You'll see this often.

1 Answer

Philip Cox
Philip Cox
14,818 Points

As mentioned above, it's the way of writing or in JS.