freeCodeCamp Challenge Guide: Introducing Else Statements

Introducing Else statements


Hints

Hint 1

When the first if statement returns false the next piece of code is executed/evaluated (like return, if or else statements).

Hint 2

Sometimes if (condition) statements can be replaced by else {code to execute instead} statements (in essence you are telling your function to do “y” if it can’t do “x” instead of specifying “x” several times) .


Solutions

Solution 1 (Click to Show/Hide)
function testElse(val) {
  var result = "";
  // Only change code below this line

  if (val > 5) {
    result = "Bigger than 5";
  } else {
    result = "5 or smaller";
  }

  // Only change code above this line
  return result;
}

// Change this value to test
testElse(4);

Code Explanation

The function first evaluates if the condition val > 5 evaluates to true. If it doesn’t, it executes the next statement (else { return "5 or smaller";}).

Relevant Links

3 Likes

solution:

function testElse(val) {
var result = “”;
// Only change code below this line

if (val > 5) {
result = “Bigger than 5”;
}

else {
result = “5 or Smaller”;
}

// Only change code above this line
return result;
}

// Change this value to test
testElse(4);

When I run the code in the console the result is “5 or smaller”. Yet the “Run Test” function says testElse(5) should return “5 or Smaller” and won’t pass. Must be a :bug:

  var result = "";
  // Only change code below this line
  
  if (val > 5) {
    result = "Bigger than 5";
  } 
  
  else {
    result = "5 or smaller";
  }
  
  // Only change code above this line
  return result;
}

// Change this value to test
testElse(5);
6 Likes