How Can I Use Ternary Conditional Operator Without Else?

I got a code block like this

const numbers = [1, 2, 3, 4, 5, 6];

const newNumbers = numbers.reduce((acc, num) => {
  acc.push(num > 3 ? num : null);
  return acc;
}, []);
console.log('new Numbers', newNumbers);
//returns new Numbers,[null, null, null, 4, 5, 6]

But I don’t want null values to be pushed in array. I want to perform the action like this but without if:

const newNumbers = numbers.reduce((acc, num) => {
  if (num > 3) {
    acc.push(num);
  }  
  return acc;
}, []);
console.log(newNumbers);
//returns new Numbers,[4, 5, 6]

>Solution :

Use && instead of ?,

const numbers = [1, 2, 3, 4, 5, 6];

const newNumbers = numbers.reduce((acc, num) => {
  num > 3 && acc.push(num)
  return acc;
}, []);
console.log(newNumbers);

//returns new Numbers,[4, 5, 6]

Leave a Reply