Conditional Functions
You can use if conditions to call other functions.
function double() {
console.log("Will double the number");
return x * 2;
}
function run(operation) {
if (operation === "double") {
return double();
}
}
// Sample usage
run("double")
Or something like
function double() {
console.log("Will double the number")
}
function triple() {
console.log("Will triple the number")
}
function run(operation) {
if (operation === "double") {
return double()
}
if (operation === "triple") {
return triple()
}
}
// Sample usage
run("double") // will call the function double()
run("triple") // will call the function triple()
It is important to note that hhile code interpretation is happening top to bottom, the code execution is not necessarily top to bottom.
The functions are loaded in top to bottom, but not executed until called. You could call triple before double.
Recap
- You can call functions inside if conditions.
- Calling functions inside if conditions allows your program to handle more complicated use cases.
- The code is interpreted from top to bottom.
- The code execution will follow your program logic. It will follow the if conditions and the function calls.