Home > Software design >  Is my understaning correct or am I wrong? (probably the second one)
Is my understaning correct or am I wrong? (probably the second one)

Time:06-30

A piece of code Im trying to fully understand:

const words = ['chair', 'music', 'pillow', 'brick', 'pen', 'door']; 
 
const shortWords = words.filter(word => {
  return word.length < 6;
});

My current assumption is that shortWords is a function that is having another function passed in as a parameter.

So shortWords is to use .filter on the words array. The argument (which is also a function?) thats passed into the shortWords function is supposed to return all words with a length less than 6 letters from the array.

Is my understaning correct or am I missing something?(again, probably the second one...)

CodePudding user response:

Yes, you are correct except the fact that shortWords is a variable that stores an array returned by .filter function.

The types of words is an array.

const words = ['chair', 'music', 'pillow', 'brick', 'pen', 'door'];

Array.filter is a method/function that allows you to loop through the array. As the name suggests, it is used to filter the array and create a new array.

Array.filter accepts a function as a parameter. In your provided snippet you have passed an arrow function as a parameter inside the filter method.

This is similar to the following code with simple function:

function filterFunctionAsParam(word) {
  return word.length < 6;
}
const shortWords = words.filter(filterFunctionAsParam);

The filter method does not change the array it acts upon. That is it does not mutate words array. The value of words array does not change. Rather it returns a filtered array. shortWords is that filtered array.

For each array element, if the condition returned by the filterFunctionAsParam is true, the element is returned by the filter function.

This can also be achieved with Array.map, Array.reduce methods.

CodePudding user response:

My current assumption is that shortWords is a function that is having another function passed in as a parameter.

No, filter is a function which has another function passed to it as a parameter.

It operates on an array, and calls the passed-in function on each element in the array - if it returns true then that array item is included in the result of calling filter.

  • Related