Javascript 101 – If / Else Constructs

Welcome back to the ONMedia blog, today we will briefly have a look at the primary conditional statement in JavaScript, the If / Else Construct.

The concept behind the If / Else statement is very much as it appears, it tests for a certain condition and executes code accordingly. Let’s assume we have a variable called age which is assigned to a particular person, and we wanted to find out whether they are legally allowed to order that beer at the bar. We are based in Australia of course, so the legal age is 18. So what we want to know is:

If the person is eighteen years old or older, then yes they can have a drink. Else, they will be denied. So how would we write this in JavaScript? Here is the basic syntax for the If / Else Construct:

if (condition) {
// Code if true;
} else {
// Code if false;

So easy, isn’t it! So let’s write out our age test, and if you need to recap on the conditional syntax, go and check out our earlier post on variables, conditionals and logic.

if (age >= 18) {
console.log("Go ahead, here is your beer");
} else {
console.log("I'm calling the cops");

Go ahead and try it out! Just as a quick refresher, remember than ternary operator syntax that could also be used here:

var bartenderResponse = (age >= 18) ? "Go ahead, here is your beer" : "I'm calling the cops";


Leave a Reply

Get a Quote

Call us or complete the form on the right and we'll get you a quote estimate ASAP.

Alternatively you can use one of the methods below:

Call us: 03 8528 1124

Email us: [email protected]

Close Form