Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading