1

Why is this-

const squareList = (arr) => {
  "use strict";
  const sqr = arr.filter((numbers) => {
    numbers > 0 && Number.isInteger(numbers)
  }).map((numbers) => {
    Math.pow(numbers, 2)
    })
  return sqr;
};

functionally different to this-

const squareddList = (arr) => { 
  "use strict";
  const sqr = arr.filter((numbers) => numbers > 0 && Number.isInteger(numbers)).map((numbers) => Math.pow(numbers, 2))
  return sqr; 
}

when the only difference between them is whitespace and curly braces?

When you pass an arbitrary array to both functions, the first returns an empty array and the second returns an array which has been filtered to only include positive integers and then squared.

withwavy
  • 33
  • 5
  • The inner lambda passed to `arr.filter` in the curly braces example doesn't have a `return` statement, so the function doesn't return anything and the filter returns an empty array. – Abion47 Feb 19 '19 at 21:41

2 Answers2

4

Arrow functions without curly braces implicitly return the result of the expression in the function body so:

const someFunction = () => 10
someFunction(); // Returns 10

is equivalent to

const someFunction = () => {
  return 10;
}
someFunction(); // Returns 10

and is NOT equivalent to:

const someFunction = () => {
  10;
}
someFunction(); // Returns undefined
Justin Reusnow
  • 290
  • 3
  • 9
  • Yup. Other languages such as C# work in a similar fashion, but you'd get a design time error as there's no syntax support for implicit "return" statement. – joelmdev Feb 19 '19 at 21:46
3

The difference is because in the first one you don't return the values. In arrow function, if you put curly brackets you need to return the value, if not the values are returned.

const squareList = (arr) => {
  "use strict";
  const sqr = arr.filter((numbers) => {
    return numbers > 0 && Number.isInteger(numbers)
  }).map((numbers) => {
    return Math.pow(numbers, 2)
  })
  return sqr;
};

This will work.

Malekai
  • 4,765
  • 5
  • 25
  • 60
arielb
  • 392
  • 3
  • 10