Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

29
Views
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]
4 months ago · Santiago Trujillo
3 answers
Answer question

0

How Can I Use Ternary Conditional Operator Without Else?

No. The conditional operator always has to "return" a value. Imagine it was possible to leave out the alternative (e.g. arr.push(num > 3 ? num)), what value would be pushed to the array?

In this specific case there is a better tool for the job: Array#filter:

const newNumbers = numbers.filter(num => num > 3)
4 months ago · Santiago Trujillo Report

0

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]

4 months ago · Santiago Trujillo Report

0

You can always do:

num > 3 ? acc.push(num) : {}
4 months ago · Santiago Trujillo Report
Answer question
Find remote jobs