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 Basics (Retired) Making Decisions with Conditional Statements Introducing Conditional Statements

Carleen Hall
seal-mask
.a{fill-rule:evenodd;}techdegree
Carleen Hall
Front End Web Development Techdegree Student 3,158 Points

"else if" conditional statement

,,, I am not sure what the answer is to the quiz regarding the "else if” conditional statement can someone tell me what is the correct answer and how they came about it? Thanks

After this code runs, what is the value of the variable itemToBuy?

var itemToBuy = ''; 
var savings = 1000; 
if ( savings > 500 ) { 
    itemToBuy = 'Computer'; 
} else if ( savings > 200 ) {
    itemToBuy = 'Phone'; 
} else if ( savings > 0 ) { 
    itemToBuy = 'Dinner'; 
} else { 
    itemToBuy = '...still saving...'; 
}

Here are the multiple choice answers.

Computer

Phone

Dinner “...still saving…" ,,,

2 Answers

Nathan Dalbec
Nathan Dalbec
17,111 Points

The if, else if, else conditional is essentially asking the computer if the expression in the parenthesis following the "if" is true in order to decide if it should run the following code in the curly braces.

if (isThisTrue) {
  //if so, run whatever is here
}

But if it is not true, then it goes to the next conditional (the else if) and asks if that is true, and if there is and "else" conditional, and none of the conditionals before it are true, the else gets run. But remember that if one is found to be true, it doesn't ask the else if, nor run the else.

So go through one at a time, and consider this expression, first it asked, is savings greater than 500? savings is 1000, so the expression is true and therefore itemToBuy will be set to 'Computer'.

Erick Martinez
Erick Martinez
2,894 Points

Thank you for this. I understand it a lot better now.