-1

I filter out every person who falls between the ages of 13 and 19. It works with a normal callback function:

let peoples = [
    {name: "Mohan",age: 65},
    {name: "Raj",age: 15},
    {name: "Sam",age: 13},
    {name: "Tamil",age: 3},
    {name: "selva",age: 25},
    {name: "siva",age: 16},
    {name: "Ram",age: 18},
]

let range = {
    lower: 13,
    upper : 16
}

let teenagers = peoples.filter(function(people){
    return ( people.age >= this.lower && people.age <= this.upper);
},range);
console.log(teenagers);

However, the arrow function it gives an empty array:

let peoples = [
    {name: "Mohan",age: 65},
    {name: "Raj",age: 15},
    {name: "Sam",age: 13},
    {name: "Tamil",age: 3},
    {name: "selva",age: 25},
    {name: "siva",age: 16},
    {name: "Ram",age: 18},
]

let range = {
    lower: 13,
    upper : 16
}

let teenagers = peoples.filter((people) =>{
    return (
        people.age >= this.lower && 
        people.age <= this.upper
        );
},range);

console.log(teenagers);

How to access the context object with this?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
MOHANRAJ M
  • 11
  • 1
  • https://www.w3schools.com/js/js_arrow_function.asp#:~:text=In%20short%2C%20with%20arrow%20functions,that%20defined%20the%20arrow%20function. – cmgchess Jun 15 '22 at 07:53
  • instead just `return people.age >= range.lower && people.age <= range.upper` – cmgchess Jun 15 '22 at 07:55

1 Answers1

0

This happens because lambda functions (arrow) get the context of where they're defined, in this case Window, which doesn't have lower or upper props. Just use range.upper and range.lower instead of this and should work just fine.