How to use ternary operator within the map() function - JavaScript

← PrevNext →

The ternary operator in JavaScript is a conditional operator. It is used as an alternative to if...else statement. But do you know you can use the ternary operator within the .map() function. Yes you can and I'll show you how.

using conditional ternary operator within map function in javascript

Why use ternary operator within map()?

This is the syntax of a ternary operator in JavaScript.

condition ? first_expression : second_expression

Now, let's understand what the map() function does.

The array.map() function allows you to iterate or loop through an array using a callback function. It creates a new array from another array.

For example, I have an array of alpha-numeric values and I want to filter out only texts.

const arr = ['a1', 'c21', 'b9', 'cq87', 'qi8'];
document.write (arr.map(x => x.match(/\D+/g)));     // Output:  a,c,b,cq,qi

The map() (in the above example), loops through each item and using RegExp (regular expression), it will filter out the numbers and return only texts.

However, some times there will be situations where you might have to a set condition to get specific values only, from the array. In such cases you can use the Conditional "ternary operator" within the .map() function.

Here's another example.

I have an array of Birds with unique ID, the name and type of bird. I want to get birds which of type "Hawk".

This is how I'll use the conditional ternary operator within the map() and get the output I want.

<script>
  const birds = [
    {"ID": "01", "Name": "Eurasian Collared-Dove", "Type": "Dove" },
    {"ID": "02", "Name": "Bald Eagle", "Type": "Hawk" },
    {"ID": "03", "Name": "Cooper's Hawk", "Type": "Hawk" },
    {"ID": "04", "Name": "Bell's Sparrow", "Type": "Sparrow" },
    {"ID": "05", "Name": "Mourning Dove", "Type": "Dove" }
  ];

  // the condition: if the bird is a "Hawk" ? return bird name : else return blank-->
  const hawks = birds.map(bird => 
                          (bird.Type === 'Hawk') ? bird.Name : ''
                         ).join(' '); 
  
    document.write (hawks);
</script>
Try it

The method is simple. The condition is, map the array and return birds which is of type "Hawk", else return nothing.

👉 Here's another example that uses ternary operator within map() in a different scenario.

← PreviousNext →