0

I encountered an issue while working on a project and I noticed that it was as a result of the curly braces in my function... quick example

const array1 = [1,2,3,4,5,6];
const array2 = [2,4,6];

const isPresentInBothArrays1 = array2.every((number)=>{
   array1.includes(number);
});

console.log(isPresentInBothArrays1) //prints false;

const isPresentInBothArrays2 = array2.every((number)=>array1.includes(number));

console.log(isPresentInBothArrays2) //prints true;

why does isPresentInBothArrays1 with curly braces return false and IsPresentInBothArrays2 without curly braces return true?

Mosco_P
  • 5
  • 4
  • Because that's how arrow functions work https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – evolutionxbox Sep 02 '21 at 13:20
  • 1
    Does this answer your question? [Curly Brackets in Arrow Functions](https://stackoverflow.com/questions/35440265/curly-brackets-in-arrow-functions) and [Arrow function without curly braces](https://stackoverflow.com/questions/39629962/arrow-function-without-curly-braces) – evolutionxbox Sep 02 '21 at 13:20
  • 1
    Thanks...It certainly does answer my question – Mosco_P Sep 02 '21 at 13:28

3 Answers3

2

It's because of the arrow function syntax, If you write something like this:

(param1, param2) => {//some expression}

is equivalent to this:

function f(param1, param2) {
   // some expression
}

and because it does not have an explicit return statement it will return undefined by default.

However, if you omit the curly brackets and put a single expression that would be a shortcut and will return the value of that expression as the return value of the function.

So as for your question in the first form, it will return undefined from the function which evaluates to false and is not what you desire, but the second form correctly returns a boolean indicating the existence of the value.

Masked Man
  • 2,176
  • 2
  • 22
  • 41
1

you need to add return if you use curly braces:

const array1 = [1,2,3,4,5,6];
const array2 = [2,4,6];

const isPresentInBothArrays1 = array2.every((number)=>{
   return array1.includes(number);
});

console.log(isPresentInBothArrays1) //prints true;

const isPresentInBothArrays2 = array2.every((number)=>array1.includes(number));

console.log(isPresentInBothArrays2) //prints true;
Harshit Rastogi
  • 1,996
  • 1
  • 10
  • 19
1

If you omit curly braces, arrow function will implicitly return the result of the expression after the =>.

However, if you use curly braces, you'll need to write return in order to make it return something, otherwise, it will return undefined.

So, in this particular case, you'll need to write:

const isPresentInBothArrays1 = array2.every(number => {
   return array1.includes(number);
});

In case you want to have curly brackets for whatever reason.

Igor Bykov
  • 2,532
  • 3
  • 11
  • 19