0

below is javascript code with filter function. when using below code, it works perfectly-

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

but below code gives an empty array. Why?

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter((word) => {
word.length > 6;
});

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
  • 1
    In the first case, you didn't use a curly brace, so it returns the `word.length > 6` expressions output. But in the 2nd case, you've used curly brace so you have to use the return keyword to return `true/false` explicitly. – Sajeeb Ahamed Jul 11 '21 at 07:25
  • So for the 2nd case if you do something like `(word) => { return word.length > 6;}` then it will work. – Sajeeb Ahamed Jul 11 '21 at 07:26

2 Answers2

0

Whenever you use curly brackets in callback you should return something

const result = words.filter((word) => {
    return word.length > 6;
});

This will work for you

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
0

Actually, you need to return the Boolean value in function so that it filters accordingly

See-

const result = words.filter((word) => {
    return word.length > 6;
});
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30
Sanmeet
  • 1,191
  • 1
  • 7
  • 15