Skip to content
Advertisement

i dont understand this javascript return statment. its using this arrow function

can anyone explain this javascript syntax. i dont understand that return statement. Is “person” an argument to the function? if ‘yes’, from where it is passing? there is no person variable in this component. At least an elaborated version of that return statement will also help. so that i can understand

const filterBy = (term) => {
    const searchTermLower = term.toLowerCase()
    return (person) => Object.keys(person).some(prop => 
        person[prop].toLowerCase().indexOf(searchTermLower) !== -1
    )
}
const filterPerson = persons.filter(filterBy(searchTerm))

here presons is an array of objects and search term is a string.

const persons=[
{ name: 'abc', number: '123456' },
{ name: 'def', number: '44233' },
{ name: 'xyz', number: '345345' },
{ name: 'npe', number: '12312' }]

later im using this returned filterPerson for later processing. code is runnin totally fine but this arrow function in return is what confusing me. im okay to update question if any more data is needed.

Advertisement

Answer

Well, it’s just an alternative way of writing the following function in simplest terms:

const persons = [{
    name: 'abc',
    number: '123456'
  },
  {
    name: 'def',
    number: '44233'
  },
  {
    name: 'xyz',
    number: '345345'
  },
  {
    name: 'npe',
    number: '12312'
  }
];

const searchTerm = 'abc';
const filterPerson = persons.filter((person) => {
  const searchTermLower = searchTerm.toLowerCase();
  return Object.keys(person).some(prop => person[prop].toLowerCase().indexOf(searchTermLower) !== -1)
})

console.log(filterPerson);

If you notice carefully, I’m passing an anonymous function to the persons.filter function. So if I want to get all fancy, I can just write that anonymous function as a separate block and return that entire function to the persons.filter function for it to be called in multiple places in my code. Which is exactly what has been done in the snippet you posted in the question.

Here’s me trying to be all fancy:

const persons = [{
    name: 'abc',
    number: '123456'
  },
  {
    name: 'def',
    number: '44233'
  },
  {
    name: 'xyz',
    number: '345345'
  },
  {
    name: 'npe',
    number: '12312'
  }
];

const myFunctionThatWasPreviouslyAnonymous = (term) => {
  const searchTermLower = term.toLowerCase()
  return (person) =>
    Object.keys(person)
    .some(prop => person[prop].toLowerCase().indexOf(searchTermLower) !== -1)

}

const searchTerm = 'abc';
const filterPersonFancy = persons.filter(myFunctionThatWasPreviouslyAnonymous(searchTerm));
console.log(filterPersonFancy)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement