-
Notifications
You must be signed in to change notification settings - Fork 2
Challenge Logical Order In If Else Statements
Order is important in if
, else if
and else
statements.
The loop is executed from top to bottom so you will want to be careful of which statement comes first.
Take these two functions as an example.
function foo(x) {
if (x < 1) {
return "Less than one";
}
else if (x < 2) {
return "Less than two";
}
else {
return "Greater than or equal to two";
}
}
And the second just switches the order of the statements:
function bar(x) {
if (x < 2) {
return "Less than two";
}
else if (x < 1) {
return "Less than one";
}
else {
return "Greater than or equal to two";
}
}
While these two functions look nearly identical, if we pass a number to both we get different outputs.
foo(0) // "Less than one"
bar(0) // "Less than two"
So be careful while using the if
, else if
and else
statements and always remember that these are executed from top to bottom. Keep this in mind placing your statements accordingly so that you get the desired output.
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links