Home > front end >  How filter works in this function?
How filter works in this function?

Time:12-16

I wrote this code while ago and now when I look at it I don't understand what "upPrice" doing here. Is is a variable? If so, how it works without declaration? If it is function parameter, I didn't passed it anywhere. Please help me to understand what it is and how it works.

 const items = [
    { name: 'Bike', price: 100 },
    { name: 'TV', price: 200 },
    { name: 'Album', price: 10 },
    { name: 'Book', price: 5 },
    { name: 'Phone', price: 500 },
    { name: 'Computer', price: 1000 },
    { name: 'Keyboard', price: 25 },

]
const filteredItems = items.filter((item) => upPrice = item.price > 50)
console.log(filteredItems); 

When I delete upPrice, code still works. But I want to understand what is it?

CodePudding user response:

upPrice isn't actually doing much in that function. The expression item.price > 50 is being stored into upPrice, which will always be a boolean value - and that value is "returned" to the filter function, which determines if that item should be kept or filtered out.

So really upPrice = can be removed safely.

Caveat: You may want to check if you have a global variable (or nearby local variable) named upPrice, as I believe you could be updating that variable from within the filter function... Though this seems like very bad practice & I would definitely never recommend doing that :D

CodePudding user response:

It can also be written like this:

const filteredItems = items.filter((item) => {
  upPrice = item.price > 50;
  return upPrice;
})

You can declare a variable without var/let/const. It just creates it as a global variable. Not usually desired.

upPrice is storing the result of "is item.price greater than 50?", a boolean value which is used to decide whether or not to filter out the current item.

Really, upPrice isn't needed. You can just return the boolean value directly without storing it first:

const filteredItems = items.filter((item) => {
  return item.price > 50;
})

Or:

const filteredItems = items.filter((item) => item.price > 50)

CodePudding user response:

Hi you are here filtering data of const items and in that lambda function you are just storing into upprice nothing more it is waste of memory nothing else

if you remove it though you can do it as you mentioned earlier

  • Related