Learn about JavaScript ELSE STATEMENTS

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.

 var name = "Bob";
 if(name == "Tony") {
 alert("Access Granted!");
 else {
 alert("Access Denied!");

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

Connected through code, Choose Your Platform!

About the Author: Bernard Aybout

In the land of bytes and bits, a father of three sits, With a heart for tech and coding kits, in IT he never quits. At Magna's door, he took his stance, in Canada's wide expanse, At Karmax Heavy Stamping - Cosma's dance, he gave his career a chance. With a passion deep for teaching code, to the young minds he showed, The path where digital seeds are sowed, in critical thinking mode. But alas, not all was bright and fair, at Magna's lair, oh despair, Harassment, intimidation, a chilling air, made the workplace hard to bear. Management's maze and morale's dip, made our hero's spirit flip, In a demoralizing grip, his well-being began to slip. So he bid adieu to Magna's scene, from the division not so serene, Yet in tech, his interest keen, continues to inspire and convene.