Getting Started
Level 1
- 4 - Comments
- 5 - Displaying Text
- 6 - Variables - Let
- 7 - Variables - Constants
- 8 - Arithmetic Operators
- 9 - Functions
- 10 - If/Else Statements
- 11 - Comparison Operators
- 12 - If/Else Loops
- 13 - Boolean Operators
- 14 - Level 1 Complete!
Level 2
Level 3
Useful Links
Step 12 - If/Else Loops
Hmm, but what if we have 4 arithmetical operations in our calculator? Well, we can use an if - else if - else structure.
const number = 7;
if (number > 7) {
console.log('Our number is bigger then 7');
} else if (number < 7) {
console.log('Our number is smaller then 7');
} else {
console.log('Our number is equal to 7');
}
Tip:
We can use any number of ‘else if’ statements in a row. The first one that is true will be the only one that runs.
Challenge:
Let’s create 2 more functions and name them ‘divide’ and ‘multiply’.
Answer
function divide(number1, number2) {
return number1 / number2
}
function multiply(number1, number2) {
return number1 * number2
}
Challenge:
Then let’s extend our ‘if else’ check that we have already created by adding
- ‘else if’ operator is equal to
-
- callsubtract
function, - ‘else if’ operator is equal to
/
- calldivide
function, - ‘else if’ operator is equal to
*
- callmultiply
function - else console.log - “Sorry, we don’t know this operator”.
Answer
const operator = "+"
const number1 = 10
const number2 = 6
if (operator === "+") {
console.log(add(number1, number2))
} else if (operator === "-") {
subtract(number1, number2)
} else if (operator === "/") {
divide(number1, number2)
} else if (operator === "*") {
multiply(number1, number2)
} else {
console.log("Sorry, we don't know this operator")
}