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 trialAbir Ahmed
Courses Plus Student 8,616 PointsWhy 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
Cindy Lea
Courses Plus Student 6,497 PointsIn the if statement the conditions are tested from top to bottom until it finds a condition that matches. In this case the first condition matched: savings is equal to 1000, so 1000 is greater than 500 so its true. Once a condition is met in an if staement it drops out of the loop and continues onto the rest of the code. Only one condition in an if statement can work (if there is one that matches).
Abir Ahmed
Courses Plus Student 8,616 PointsAbir Ahmed
Courses Plus Student 8,616 PointsThanks Cindy Lea :)