Nemank Yadav
Nemank Yadav

Reputation: 11

Using Ternary operators with filter function in javascript

I am new to coding and am starting with Javascript with a 30 Day vanilla javascript coding challenge from Wes Bos. I want to know why this works perfectly

const in1500 = inventors.filter((a)=>{if(a.year>=1500 && a.year<1600) return 1})
console.table(in1500)

this gives a blank result

const in1500 = inventors.filter((a)=>{(a.year>=1500 && a.year<1600) ? 1 : -1})
console.table(in1500)

and this gives me the whole array

const in1500 = inventors.filter((a)=>(a.year>=1500 && a.year<1600) ? 1 : -1)
console.table(in1500)
//I just removed the angular brackets

Upvotes: 0

Views: 1563

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386746

Array#filter expects a value which can be converted to true for items in the result array.

Return values which can be converted to false are filterd out.

Your approaches:

  1. Arrow functions with a function block returns undefined by default. You return 1 which is a truthy value (like any number without zero or NaN, every non empty string, every array or object or function, and of course true), what meas this value can be converted to true.

  2. Here you have a function block and return nothing. The default value is undefined, which is falsy (like false, zero, NaN, '', null), the opposite of truthy.

  3. You simply return a truthy value (as both 1 and -1 is truthy), all items are in the result set.

The shortest approach is to use an arrow function without function block and return just the result of the condition.

const in1500 = inventors.filter(a => a.year >= 1500 && a.year < 1600);

A use of a conditional (ternary) operator ?: inside of the function is superfluous, because you need to return either a truthy or falsy value, which is more code and does not make sense.

Upvotes: 3

Nishant
Nishant

Reputation: 466

in the second case, you have not given a return, that's why it's giving a empty result.

let inventors = [1500, 1501, 1505, 1550];
let in15001 = inventors.filter((a) => {
  if (a.year >= 1500 && a.year < 1600){ return 1}
  else return -1;
})
console.log(in15001)

let in15002 = inventors.filter((a) => {
  return (a.year >= 1500 && a.year < 1600) ? 1 : -1
})
console.log(in15002)


let in15003 = inventors.filter((a) => (a.year >= 1500 && a.year < 1600) ? 1 : -1)
console.log(in15003)

Upvotes: 0

Related Questions