I'm just getting back into coding and I'm curious as to why the checkNum(oddNum)
function outside of the if statement is still being called?
If I'm understanding scoping correctly, shouldn't the checkNum
function only be able to be called within the scope of the if statement?
Yes I am aware there is an easier way to do the check and the function is not required, but I am just practicing and trying to understand scoping. =D
let evenNum = 2;
let oddNum = 3;
if (evenNum < 5) {
checkNum(evenNum);
function checkNum(evenNum) {
let isEven;
isEven = evenNum % 2;
if (isEven === 0) {
console.log("The number is even");
} else if (isEven != 0) {
console.log("The number is odd");
} else {
console.log("The number is greater than 5")
}
}
}
checkNum(oddNum);
EDIT:
As per javascript.info, this will not work, but the code seems to be similar?
let age = 16; // take 16 as an example
if (age < 18) {
welcome(); // \ (runs)
// |
function welcome() { // |
alert("Hello!"); // | Function Declaration is available
} // | everywhere in the block where it's declared
// |
welcome(); // / (runs)
} else {
function welcome() {
alert("Greetings!");
}
}
// Here we're out of curly braces,
// so we can not see Function Declarations made inside of them.
welcome(); // Error: welcome is not defined