Learn about JavaScript ELSE STATEMENTS: Else statements are used with if statements to make web pages even more interactive.
You use an else statement after an if statement to change which block of code is run by your browser. If the condition of your if statement is false, your browser will run the alternative else statement.
<script> var name = "Bob"; if(name == "Tony") { alert("Access Granted!"); } else { alert("Access Denied!"); } </script>
Else statements are written in exactly the same way as if statements – you just have to use the else keyword instead. You put the code you want to run inside curly braces { }. Let’s take a look at an example of an if statement and an else statement working together:
If we run this code in our browser an alert will pop up. The value of our variable is the name of one of the cyber criminals (Tony) and not equal to (==) Bob. Because the condition of the if statement was false, our browser ran the else statement. But if the value of our variable had been equal to (==) Bob and the condition of our if statement had been true, the else statement would not have run. The if statement would have run instead, and the “Access Granted“ alert would have popped up.
Understanding how this logic works and applying it effectively is a programming skill acquired in time.
Related Links:
Online JavaScript Compiler. Code on the go.
JavaScript Glossary – Else Statements