DEV Community

Cover image for JavaScript basics if...else statement
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

JavaScript basics if...else statement

I sometimes forget that I write about content in a medium to advanced kind of matter.

In these JavaScript basics series, I'll be looking at some more fundamental topics of JavaScript, so you get a good idea of how to use these methods.

In this article, we'll be looking at using if...else statements in JavaScript.

A JavaScript if statement

An if statement can be used to execute code only when a specific condition is met.

Let's say we have a variable and want to evaluate whether it's true or false.

let our_var = true;
if(our_var === true) {
    // Execute this code if true
    console.log('Value is true);
}
Enter fullscreen mode Exit fullscreen mode

In this case when we are checking boolean values, we don't need to specify the specific value so we can do this:

if(our_var) {
    // Execute this code if true
    console.log('Value is true);
}
Enter fullscreen mode Exit fullscreen mode

You can also check if the value is false, like this:

if(!our_var) {
    // Execute this code if false
    console.log('Value is false);
}
Enter fullscreen mode Exit fullscreen mode

We can even write this as a one-liner, but most linters will want to see the brackets for neatness.

if (our_var) console.log('Value is true');
Enter fullscreen mode Exit fullscreen mode

JavaScript if...else statement

Often you also want to execute some code if the first condition is not met.
We can achieve this by using the else statement as well.

if (our_var) {
  console.log('Condition is met');
} else {
  console.log('Condition is not met, fallback?');
}
Enter fullscreen mode Exit fullscreen mode

And you can even bind another if statement to this else, making it super powerful.

Let's say you want to check multiple conditions after each other.

if (our_var) {
  console.log('first condition met');
} else if (our_second_var) {
  console.log('Second condition was met!');
} else {
  console.log('No condition was met');
}
Enter fullscreen mode Exit fullscreen mode

You can make these as big as you want, but often you might want to consider using other solutions for bigger statements.

JavaScript Ternary Operator

The JavaScript ternary operator is a quick way to express conditions and is often used for shorthand if...else.

The Syntax looks like this:

condition ? truthy : falsy;
Enter fullscreen mode Exit fullscreen mode

If we take our example, we could write code like this:

our_var ? console.log('Condition is met') : console.log('Condition not met');
Enter fullscreen mode Exit fullscreen mode

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (0)