The right usage of braces within arrow function within Array.prototype.filter [duplicate]

(function (){
  console.log([0, 1, 2, 3].filter(i => {i % 2 == 0}));
})();
// Array[]

I want to print an array that contains only even numbers, that is 0 and 2 in the case above. Array.prototype.filter along with an arrow function are used for this purpose.

The above code returns an empty array. However, if I remove braces, the code works as expected.

(function (){
  console.log([0, 1, 2, 3].filter(i => i % 2 == 0));
})();
// Array[0, 2]

Can someone explain why it happens? I always used arrow functions with braces and they worked just fine but it seems to me that there are caveats.

1

The body of an arrow function is either an expression, whose value is the value returned by the function, or a block of statements, similar to a regular function.

i => i % 2 == 0 has an expression as the body and is equivalent to:

function(i) {
  return i % 2 == 0
}

i => { i % 2 == 0 } has a block of statements as the body and is equivalent to:

function(i) {
  i % 2 == 0
}

It does not return anything. Therefore Array.filter() concludes that none of the array items matches the filter and returns [].

If you wrap the arrow function body in curly braces you have to explicitly mention what it returns:

i => { return i % 2 == 0 }

This is equivalent to i => i % 2 == 0 and not worth using.
However, if the arrow function does many things and an expression cannot be used then the block of statements and the explicit return are the way to go.

Arrow functions can skip the return keyword for single-line functions.

If you add braces, it means that the function will have multiple lines and it needs to know when to return something. Therefore, you need to add a return statement.

The explicit (with braces) equivalent of

i => i % 2 == 0

would be

i => { return i % 2 == 0 }

or (in function notation)

function (i) {
  return i % 2 == 0
}

Your filter doesn’t return the expected result when you use braces because that function doesn’t return anything, which means the result is always undefined, which is falsy.

Why doesn’t it work now?

i => { i % 2 == 0 }

is equivalent to

function (i) {
  i % 2 == 0
}

The function above computes whether i can be divided by 2, but it doesn’t store or return the value anywhere.

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *