in ,

WINWIN

Single-Line If Statement with the ternary operator in Javascript

Javascript Ternary Operator

Have you ever wanted to create an if statement in javascript but in just one line? Well, this is what I’m going to be teaching you guys in this tutorial with the ternary operator.

So let me explain how to use Javascript’s ternary operator with this example. Let’s say we have 2 variables one is wheels and another is vehicles and we wanted to change the variable vehicle depending on how many wheels the vehicle has. For example, if it has 4 wheels or more we know it’s a car but if it has less than 3 wheels we can say it’s a motorcycle.

let wheels = 4;

let vehicle;

if(wheels >= 4){
  vehicle = 'car'
} else {
  vehicle = 'motorcycle'
}

We can use the ternary operator to make this into one line.

<condition> ? <return if true> : <return if false>

I do want to mention before we convert this if statement into one line that you can use parenthesis to wrap around the conditional but it’s not needed. I just like to do it to make it easier to read.

let wheels = 4;

let vehicle = (wheels >= 4) ? 'car' : 'motorcycle'

If you enjoyed this tutorial make sure you check out the courses at CodingPhase. Over 40 courses for $20 bucks and click here to try them out for 50% OFF.

Check documentation Ternary Operator

What do you think?

Written by CodingPhase

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Loading…

0

Comments

0 comments

Junior Web Developer Portfolio Review

background image opacity

How to Change a Background Image’s Opacity with CSS?