In simple terms, else
is the default action when the if
condition is not met. Any number equal to or greater than 18 will meet that condition. It is only when age
is less than 18 that the condition is not met and so falls down to the default action (when there is one).
Thank you very much for your input.
I was also confused by the following lesson statement:
The code inside the
else
statement code block will execute when theif
statement’s condition evaluates tofalse
if(false) {
console.log('The code in this block will not run.');
} else {
console.log('But the code in this block will!');
}
I read the above as…if condition is false The code in this block will not run
would be printed to the console.
If the condition is not equal to false then the condition must be true and therefore the code in the else block is executed.
So if the if statements condition is false then the code in the else statement will never execute.
That is false. The ELSE block code will only run when the truth value of the condition is falsy.
if (condition) {
// condition MUST be truthy or this block is never executed
} else {
// condition MUST be falsy or this block is never executed
}
It is the way if
statements are hardwired. ONLY true
or truthy make it thru the first gate. All others are directed to the second gate.
Did you run the code in the example given above? Try any of the following values in the condition:
''
""
undefined
null
0
They are all falsy and will all give the result in the second block (the else).