Tell us what’s happening:
In searching for an answer to this, it seems like some people have already asked, “why not just replace an “else” statement with another “if” statement?” To be clear, that is not my question.
In the lesson “Basic JavaScript: Introducing Else Statements,” we are told that the way to get some code to run if the “If” condition is false, is to use an “else” statement. Their example:
if (num > 10) {
return "Bigger than 10";
} else {
return "10 or Less";
}
BUT, in the earlier lesson “Basic JavaScript: Use Conditional Logic with If Statements,” the following example is used:
function test (myCondition) {
if (myCondition) {
return "It was true";
}
return "It was false";
}
The part I put in bold seems like it is equivalent to an “else” statement. As the lesson goes on to describe: " When test
is called with a value of true
, the if
statement evaluates myCondition
to see if it is true
or not. Since it is true
, the function returns "It was true"
. When we call test
with a value of false
, myCondition
is not true
and the statement in the curly braces is not executed and the function returns "It was false"
." So the code \return “It was false”\ executes when the condition is false… just like if you used an else statement, right?
So I guess my specific questions is, couldn’t we just drop the else statement in the initial example, and have simply:
if (num > 10) {
return "Bigger than 10";
}
return "10 or Less";
Would that accomplish the same thing? If so, then what is the point of the “else” statement?
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36
.
Challenge: Use Conditional Logic with If Statements
Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/use-conditional-logic-with-if-statements