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) Creating Reusable Code with Functions Random Number Challenge, Part II Solution

Mohammed Zeeshan
PLUS
Mohammed Zeeshan
Courses Plus Student 3,302 Points

Do we need to use else statement here?

After if statement, do we need to use else statement, so that if the boolean value returns false, the else statement runs and returns the arguments?

4 Answers

Kevin Gates
Kevin Gates
15,052 Points

Technically no.

You could have a situation where you only want to perform an action where a condition is True.

Imagine this scenario: IF I see my friend THEN I will say "Hello" to him.

If I don't see my friend, I'm not going to do anything, so I won't be saying "Hello", etc.

Else statements are helpful when you want to perform an alternative action. IF I see my friend THEN I will say "Hello" to him, ELSE I will text him later today.

In the instance above, I'm deciding to say "Hello" if I see him, but if I don't see him, then I want to text him later in the day.

Programmatically, it's the same thing. Sometimes you only want to perform an action if a condition is met. Other times you want to perform an action if a condition is met, and an alternative action if the condition is NOT met.

During the program execution, the statements written inside the if block will only be executed when the condition mentioned is true. Otherwise, if the condition is false, the next consecutive lines after the if block will be executed. It will not search for else or generate an error. In this case, I don't believe including the else would change the way the code runs at all.

Hope this helps, Dylan

Usually what I like to do if I have only two cases to cover, first I check if a condition is false then stop execution otherwise continue, for example: let something = false; if(!something) { return }; // continue