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 Local Storage Project

Why no `else` statement?

In the teacher's code for the function saveSearchString(str), I was (painfully) aware that there was no else statement following the if statement:

    function saveSearchString(str) {
      var searches = getRecentSearches();
      if(!str || searches.indexOf(str) > -1) {
        return false;
      localStorage.setItem('recentSearches', JSON.stringify(searches));
      return true;

As we all saw, this worked fine. Wouldn't this cause the function to return true in either case, or try to return both?

3 Answers

Steven Parker
Steven Parker
229,608 Points

You never need an "else" when the body of an "if" ends with a "return". The return terminates the function, so no other code within the function will be executed.

In a sense, you can say that everything after the conditional block is "else" code, because it will only run when the if condition is not true.

Thanks! Is this functionally the same as, say, a break statement, apart from the fact that a value is being returned?

Steven Parker
Steven Parker
229,608 Points

It's perhaps slightly similar. A "return" ends a function or method, a "break" ends a loop.

Perfect, thanks a lot!