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.