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

Ben Os
Ben Os
20,008 Points

? x : y; --- What is this syntax in Js?

I have seen the following code:

if (obj.a === undefined) { a = obj.b === undefined ? b : obj.b;

I know that a and b are properties of obj and I understand that the code says the following (hope I understand this correct):

If obj.a is undefined, put obj.b in it, if the value of property b is obj.b

Is my understanding of the question-mark and colon syntax accurate in this context?

Dave McFarland

3 Answers

andren
andren
28,558 Points

The ? : syntax is an example of a ternary operator.

The structure of a ternary operator is like this: (boolean) ? returnedIfTrue : returnedIfFalse.

It is basically a short way to perform a one line if/else statement.

So a = obj.b === undefined ? b : obj.b; is actually saying if obj.b === undefined is true, then set a equal to b. If it is false then set a equal to obj.b.

It is the same as this if/else statement:

if (obj.b === undefined) {
    a = b;
} else {
    a = obj.b;
}

It is just a shortened version.

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

Hi Ben Aharoni

As Andren and Aaron pointed out this is called a ternary operator. We have a short workshop you could watch called Exploring JavaScript Conditionals which includes a video about the Ternary Operator