13

I've found a weird issue.

given a filter and an array of objects, I would like to select only those objects that match the filter.

Weirdly, this doesn't work

this.state.articles.filter((article) => {
  article.category === filter 
})

while this does

this.state.articles.filter((article) => article.category === filter )

I originally thought they would evaluate the same, but it doesn't seem to be the case. Any ideas why?

mark
  • 833
  • 8
  • 21
  • The first one uses a block of code, so a return statement is needed. The second one uses the implicit return of an arrow function – ibrahim mahrir Sep 14 '18 at 14:46
  • 3
    `(article) => article.category === filter )` is `(article) => { return article.category === filter })` – epascarello Sep 14 '18 at 14:47
  • 1
    See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions#The_arrow_function_expression_(%3E) – Gabriele Petrioli Sep 14 '18 at 14:48
  • 1
    How did this get so many upvotes? Just curious--it's in the language spec, it's documented on SO and elsewhere. – Dave Newton Sep 14 '18 at 16:06
  • @DaveNewton it's difficult to find the right information, and at times it's easier just to have a conversation about certain problems people face. I guess people like to talk, even if it's on a staticish forum like SO. – mark Sep 28 '18 at 07:57
  • @mark If SO was a cafe or office water cooler, great. It's not, and has a clear mandate to reduce duplicates, reduce noise, and encourage research. – Dave Newton Sep 28 '18 at 10:48

4 Answers4

27

When you open a block {} in an arrow function, the return isn't implied anymore.

You have to write it down :

this.state.articles.filter((article) => {
  return article.category === filter 
})
Zenoo
  • 12,670
  • 4
  • 45
  • 69
8

Javascript ES6 arrow functions work in a particular manner which can best be described via an example:

let multiply1 = (number) => number * 2;
// When we are returning one value we can put this expression on the same line

// this is the same as:
let multiply2 = (number) => { return number * 2};

//when we have 1 argument we can omit the parentheses
let multiply3 = number => number * 2;


// When we want to write multiple line we have to put brackets like this:
let multiply4 = (number) => { 
console.log('inside arrow function');
return number * 2;
};

console.log(multiply1(2));
console.log(multiply2(2));
console.log(multiply3(2));
console.log(multiply4(2));

When the arrow function is returning an expression it is very convenient to not have to explicitly write the return statement and the square brackets {}. This allows for more concise code.

Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155
5

How is () => {…} different from () =>

+----+--------------------------------+---------------------------------------+
| #  | Using curly brace              | Without curly brace                   |
+-------------------------------------+---------------------------------------+
| 1. | Needs explicit return          | Returns the statement implicitly      |
| 2. | `undefined` if no return used  | Returns the value of expression       |
| 3. | return {} // ok                | {} // buggy, ({}) // ok               |
| 4. | Useful for multi-line code     | Useful for single line code           |
| 5. | Okay even for single line      | Buggy for multi line                  |
+----+--------------------------------+---------------------------------------+

Here's the examples for above differences:

Example: 1

// Needs explicit return
() => {
  return value
}
// Returns the value
() => value

Example: 2

// Returns undefined
() => {
  1 == true
}
// Returns true
() => 1 == true // returns true

Example: 3

// ok, returns {key: value}
() => {
  return {key: value}
}
// Wrap with () to return an object
() => {key: value} // buggy
() => ({key: value}) // ok

Example: 4

// Useful for multi-line code
() => {
  const a = 1
  const b = 2
  return a * b
}
// Useful for single line code
() => 1 * 2 

Example: 5

// Okay even for single line code
() => { return 1 }
// Buggy for multi-line code
() => const a = 123; const b = 456; a + b; // buggy
() => 
     const a = 123
     const b = 456
     a + b // still buggy

When using filter function, return statement is required to pass the test:

A new array with the elements that pass the test. If no elements pass the test, an empty array will be returned.

So, with the form () =>, you're implicitly returning the value, it will pass the test and works fine. But when you use () => {...}, you're not explicitly returning the statement, and won't work as you expect. It just returns an empty object.

So, to make your code work as expected, you should use the return statement:

this.state.articles.filter((article) => {
  return article.category === filter 
})

PS: I'm using the implicit and explicit word, what's exactly that in terms of JavaScript?

Implicit means JavaScript engine does it for us. Explicit means We need to do what we want. We can think similar in any terms.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
2

The difference is that when you use () => x, it really means () => { return x }, so just how the statement article.category === filter on its own dosen't do anything, { article.category === filter } dosen't explicitly return anything.

DeltaMarine101
  • 753
  • 2
  • 8
  • 24