Subscribe

JavaScript basics if...else statement

โœ๏ธ

How to use the if else statement in JavaScript

24 Aug, 2021 ยท 3 min read

I sometimes forget that I write about content in a medium to advanced 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.

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');
}

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');
}

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

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

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');

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?');
}

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');
}

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;

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

our_var ? console.log('Condition is met') : console.log('Condition not met');

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

TypeORM viewEntity

30 Mar, 2022 ยท 5 min read

TypeORM viewEntity

The Record Utility Type in TypeScript

12 Mar, 2022 ยท 3 min read

The Record Utility Type in TypeScript

Join 1509 devs and subscribe to my newsletter