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 Review Else If Clauses and JavaScript Comments

Abir Ahmed
PLUS
Abir Ahmed
Courses Plus Student 8,616 Points

Why in the following code the first condition passed so only it's code ran? Can you please explain

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...'; }

1 Answer

Alexander Smith
Alexander Smith
10,476 Points

In an if else statement, think of each if, else if, then finally else statement used as paths. the program will go through until a condition is met and will go down that path and only that path. Since your var savings = 1000 is greater then 500, it goes down that path. If your var savings is less then 500 in your if condition, it would check your next else if condition and if that condition is met (true) the program will run that block of code and so on and so on.

So if your var savings = 1000, buy computer. if var savings = 201, buy phone if var savings = 199, buy dinner if savings = 0, still saving