0

I've understood how to use filter, but seeing this answer to this exercise: Eloquent JavaScript confuses me (you can see the code when you click 'look at the solution'. Just what is the difference between:

let counted = countBy(text, char => {
  let script = characterScript(char.codePointAt(0));
  return script ? script.direction : "none";
}).filter(({name}) => name != "none");

and:

let counted = countBy(text, char => {
    let script = characterScript(char.codePointAt(0));
    return script ? script.direction : "none";
}).filter(name => name != "none"); //The difference is here and when I tried this, it did not work

What I'm familiar with is using ... .filter(something => condition); and it will return an array of all the items from the original array that fulfills said condition. I tried changing the above code to ... .filter(script => script.name != "none") and it worked. So what exactly does ({name}) do so specially that I don't have to type that long?

Richard
  • 7,037
  • 2
  • 23
  • 76
  • it looks like destructuring. but I'm not sure `{name} => name` is valid or not. – apple apple Aug 18 '18 at 13:08
  • I thought object destructuring had to be wrapped in brackets when used in an arrow function argument. – Cameron Martin Aug 18 '18 at 13:16
  • @CameronMartin I've fixed the code. It didn't work if it doesn't have braces, is that just the rule to using object destructuring in an arrow function argument? – Richard Aug 18 '18 at 13:17
  • @WealthyPlayer I _think_ the only time the parentheses can be omitted is when the parameter is just an identifier. So you need parentheses when using array destructuring, object destructuring and default parameters. – Cameron Martin Aug 18 '18 at 13:31
  • @CameronMartin I see, thank you! – Richard Aug 20 '18 at 05:31

1 Answers1

1

That's object destructuring in action. Instead of passing an object x into the filter and then comparing to x.name, you're just destructuring name right out.

.filter(({name}) => name != "none");

is equivalent to

.filter(x => x.name != "none");

More on destructuring here

Cameron Martin
  • 5,952
  • 2
  • 40
  • 53
Jamie Weston
  • 351
  • 4
  • 14
  • 1
    I see, thank you! I've forgotten Object Destructuring I've learnt before in the books, I'll read again. – Richard Aug 18 '18 at 13:16