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 The Conditional Challenge Solution

Randolph Wang
Randolph Wang
3,614 Points

'If else' statement best practices

Hey guys,

The latter half of my code giving the rankings looked like this:

if (counter === 5) {

document.write('You got a Gold star!');

} else if (counter === 3 || counter === 4) {

document.write('You got a Silver star!');

} else if (counter === 1 || counter === 2) {

document.write('You got a Bronze star!');

} else {

document.write('Sorry, but you are unfortunately unranked.');

}

In the video, Dave used the '>= 3', '>=1' and etc. The more I looked at it, Dave's code seemed to be more efficient. Is Dave's way a more common practice? Furthermore, is his code more Efficient?

1 Answer

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,860 Points

Hi Randolph Wang

In the practice of getting the most "bang for your buck" and for readability, Dave's is better and the common practice.

If something can be done shorter and with less code, it is often (though not always) more readable and to the point. While both code blocks achieve the same end result, the former it a bit cumbersome and lengthy.

else if (counter === 3 || counter === 4) ==> 40 keystrokes
else if (counter >=3) ==> 21 keystrokes

Almost half the amount of typing. Now imagine this over 1000s (maybe tens or hundreds of thousands) of lines of code... That's lots of extra typing. Also this example reads much more clear and quickly, which is also very important. The first, you have to think for a second ==> "anything that is a 3 or anything that is a 4".
The second ==> "anything 3 or larger"

See the difference? I hope this did answer you question and provide insight as to why one way is better.

Keep Coding! :) :dizzy: