1

I am using the filter method in javascript and I noticed that it returns undefined if I use curly brackets but returns the array correctly if I delete them. Interestingly enough, the Atom extension automatically adds them when using the Array filter method.

This code works:

const filterTest = (nums) => 

nums.filter(test)

const test = (el) => el % 2 == 1
const rain = [1, 2, 5, 7, 101, 9, 108, 12, 15, 19];
console.log(filterTest(rain))

The first code works without the curly brackets but adding the curly brackets for the block of code produces undefined. Why is this?

Alex Kudryashev
  • 9,120
  • 3
  • 27
  • 36
Chris Matthews
  • 446
  • 2
  • 5
  • 14
  • 4
    If you use braces, you need to explicitly `return` a value. `el => { return el % 2 == 1}` – Mark Jun 28 '19 at 19:01
  • 1
    Basics of arrow function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – epascarello Jun 28 '19 at 19:01

2 Answers2

2

Arrow functions are quite handy for small functions and IIFEs in part because of this nuanced behavior with braces.

Without curly braces, arrow functions support a single operation (be that a function call, math operation, etc.) and return the output of that operation as the return value of the function. This makes simple one-liners a cinch to write and understand because you can remove all the unnecessary fluff, leaving only the meat of the function.

If you want to have multiple operations in your arrow function definition, you need to add curly braces like with a normal function definition, then include a return statement to define which operation you want to return. If you don't include a return here, it's the same as a normal function without a return.

In other words, this:

let oneUpMe = (a) => { a + 1; }
// Braces enclose one or more statements like a normal function

is effectively the same as

function oneUpMe(a) { let b = a + 1; b; }
// But on its own, just calling b does nothing; same with a+1 in the previous example.

in that because there's no return statement, the work inside is never returned, but

let oneUpMe = (a) => a + 1;

will return the proper result because without the braces and with only one statement, the return statement is implied.

IronFlare
  • 2,287
  • 2
  • 17
  • 27
0

simply :

var a = () => 0 
// without brackets it means return the value after the arrow


var b = () => {console.log(0);return0} 
// with brackets is the same as the default function declaration 
// which works exactly like 
function b(){console.log(0);return0}
Abdelillah Aissani
  • 3,058
  • 2
  • 10
  • 25