How to Assign Variable Values Using the Ternary (?) and Logical AND (&&) Operators in JavaScript

Bridge going into forest.

The ternary (?) and logical AND (&&) operators in JavaScript can be used in place of an if…else statement, and can give you cleaner code. Here is a preview of how we will use it:

let carQuality
car === 'Corolla' && (carQuality = 'high')

See the video I recorded for this here! ▶️

Let’s look at the full example. First, consider the below function and the if…else inside of it. If we pass ‘Corolla’ to the function, it will return ‘high’:

Using if…else

function getCarInfo(car){
  let carQuality 
  if (car === 'Corolla') {carQuality = 'high'}
  return carQuality 
}

getCarInfo('Corolla') //returns 'high'
getCarInfo('Malibu') //returns 'undefined'

Instead of using if…else, we can use the logical AND operator:

Using logical AND (&&)

function getCarInfo(car){
  let carQuality 
  car === 'Corolla' && (carQuality = 'high')
  return carQuality 
}

getCarInfo('Corolla') //returns 'high'
getCarInfo('Malibu') //returns 'undefined'

Here we can see that the if…else has removed the necessity to use “if”. Note that we need to wrap the variable assignment in parentheses, otherwise the code will throw an error. The length of the code is similar, but it provides us with options that can sometimes allow us to make cleaner code. Another way we can do this is using the ternary operator:

Using ternary (?)

function getCarInfo(car){
  let carQuality 
  car === 'Corolla' ? carQuality = 'high' : null
  return carQuality 
}

getCarInfo('Corolla') //returns 'high'
getCarInfo('Malibu') //returns 'undefined'

Instead of using “&&”, above we use “?”. Unless we’re going to add more options, however, we need to add “: null” or “: undefined” at the end, because the ternary operator requires multiple options. If we want multiple options, we can do like this:

function getCarInfo(car){
  let carQuality 
  car === 'Corolla' ? carQuality = 'high' : carQuality = 'low' 
  return carQuality 
}

getCarInfo('Corolla') //returns 'high'
getCarInfo('Malibu') //returns 'low'

Note that here it is not necessary to wrap the variable assignments in parentheses. We could also rewrite the above code like this:

function getCarInfo(car){
  let carQuality 
  carQuality =  car === 'Corolla' ? 'high' : 'low' 
  return carQuality 
}

getCarInfo('Corolla') //returns 'high'
getCarInfo('Malibu') //returns 'low'

That’s It!

I hope you find these notations useful. I myself enjoy using them at times when writing functions, or when using React.

Cheers! ?

Subscribe to new blog posts