Categories
Arrays JavaScript Uncategorised

Javascript Array Methods: forEach(), map(), filter() and reduce()

What is forEach() and when to use it?

The method forEach() lets us run a provided function for every element in our array. The method will run our callback function with 3 arguments. The first argument is the value of the current index, the second argument is the actual index, and the third parameter is a reference to the array where we are applying the forEach() method. We can also pass a second parameter to the forEach() method to use as ‘this’ value when to call our callback function.

const array = ['one', 'two', 'three'];

array.forEach(element => console.log(element));

/* 
  expected output:
  "one"
  "two"
  "three"
*/

We have to remember that for Each method return ‘undefined’. This is the reason why if we want to do some processing with the data of the array is better to look at a different method like map() or filter().

What is map() and when to use it?

Method map() will create a new array with the results of the callback function call for every value in our array. In this case, our callback will run with the same three arguments as forEach() with a big difference, now we are going to be able to create a new array with the returns of the callback function. Like in forEach(), we can pass a second parameter to map() to indicate the value use as this when our callback function is called.

const array = [1, 2, 4, 6];

const newArray = array.map(element => x + 2);
console.log(newArray);

// expected output: Array [3, 4, 6, 8]

You will find map() method very useful when you need to process the information in an array to generate a new array.

What is filter() and when to use it?

The method filter() will test every element of the array against our test in the callback function returning a new array with the values that return true in the callback. Like forEach() and map(), we are going to have three arguments in our callback function and an optional parameter to assign the value of this inside our callback function, but in this case, the array returned by the filter() method has to meet the condition in our call back.

const numbers = [25, 28, 10, 4, 8, 18];

const result = numbers.filter(number => number > 8);
console.log(result);

// expected output: Array [25, 28, 10, 18]

Filter() will help you get the information you need into a new array. Every time that you need to pick into an array to extract the useful information, filter() will do the job for you.

What is reduce() and when to use it?

Reduce() call a callback function in every value of the array to return a single value. In this case, the arguments are different from the last three methods mentioned before. We are going to have three arguments in our callback function. The first argument is the accumulator, this can be the return value of the last callback invocation or the initial value if provided. The second argument is the current value is being processed. These two arguments are required in our callback. The third argument is the current index and the fourth argument is the array where reduce() was called. In this case, the second parameter of reduce() will be an optional initial value.

const numbers = [2,3,4,5];
const reducer = (accumulator, currentValue, index) => accumulator + currentValue;

//2 + 3 + 4 + 5
const sum = numbers.reduce(reducer);
//accumulator+2+3+4+5
const sunWithInitialValue = numbers.reduce(reducer, 1);

console.log(sum);
// expected output: 14

console.log(sum);
// expected output: 15

The initial value parameter is very important because it will be used as the first argument (accumulator). In case of no provide this initial value for the accumulator, the first index value of the array been processed will be the initial value for our accumulator.

It’s important to remember that we can build complex reducer functions that help us solve more complex problems. We can add a condition inside our reducer too, for example, add only the even numbers.

const numbers = [2,3,4,5];
const reducer = (accumulator, currentValue, index) => { 
if ( currentValue % 2 === 0){
return accumulator + currentValue;
};

return accumulator
};

//2 + 4
const sumEven = numbers.reduce(reducer);

console.log(sumEven)
// expected output: 6

There is no reason to reinvent the wheel and write complex for loops when we have available all this build in methods in the language that helps us write clean code that is pleasing to read.

This blog is part of my learning process. if you have something to say about this post, please contact me or leave a comment. I’ll be more than happy to hear what others have to say and learn from them.

Happy Coding! 🙂

Categories
ES6 JavaScript

Intro to Destructuring JavaScript Objects and Arrays

What is Destructuring?

Destructuring or Destructuring assignment is a syntax we can use to extract properties from objects or values from arrays in JavaScript assigning then to a variable. Let’s use the next object as a starting point.

const car = {
  maker: 'Toyota',
  model: 'Corolla',
  color: 'Yellow',
  engine: {
    Displacement: 2.0,
    cylinders: 4
  },
  license_plate: 'ASSF4287',
};

Destructuring Objects

Sometimes we need access to the properties values of an object through a variable, something like:

const license_plate = car.license_plate;
const maker = car.maker;
const color = car.color;

Using this syntax creates repetitive code and you’ll find yourself typing the same code again and again. This last snipe can be reduced to one line using the new destructuring syntax from ES6 as follow.

const { license_plate, maker, color } = car;

console.log(license_plate); //'ASSF4287'
console.log(maker); //'Toyota'
console.log(color); //'Yellow'

This line of code simplifies the way that we can create high-level variables to access those properties that we need in a faster and cleaner way. We can also access nested object properties or use default values in case the property we try to access doesn’t exist.

const {
  license_plate = 'unknown', //Using a default value.
  maker,
  color,
  engine: { displacement }, //Accesing nested properties.
} = car;

console.log( engine.displacement ); //2

Destructuring Arrays

Like Objects, arrays can be destructuring using the new ES6 syntax. Let’s use the next array as the starting point for our examples.

const colors = [
  'red',
  'yellow',
  'blue',
  'white',
  ['metalized blue', 'metalized red', 'metalized orange'],
];

We assign values from a specific index in the array to a variable follow the old syntax, like:

const red = colors[0];
const yellow = colors[1];
const metalizedBlue = colors[4][0];

As our example for objects, this method makes us write the same thing again and again. If we use the destructuring method we can reduce all this code to one line, improving the readability and simplified our code.

const [red, yellow, , , [metalizedBlue]] = colors;

console.log(red); //'red'
console.log(yellow); //'yellow'
console.log(metalizedBlue); //'metalized blue'

In this example, we can see how easy it is to create high-level variables from the values of our array, we just have to place the name of the variable in the place of the array where is the value that we want to assign to this variable. Also, we can skip any index by leave an empty spot, besides we can access nested arrays using the same syntax rules. We can use this same syntax to create variables from an array nested in an object mixing both techniques.

Spread Syntax

Using . . . before any iterable, we can assign the rest of the items in an array to a specific variable. Let’s create a quick example.

const [red, yellow, ...otherColors] = colors;

console.log(red); //'red'
console.log(yellow); //'yellow'
console.log(otherColors);
/**['blue',
 *   'white',
 *   ['metalized blue', 'metalized red', 'metalized orange'],
 *  ];
 **/

Destructuring Function Parameters

Destructuring can be very useful to create local variables from the parameters of a function. We can require an object as parameters for our function, this way whoever uses our function in the future doesn’t need to remember the specific order of the parameters and instead.

const car = {
  maker: 'Toyota',
  model: 'Corolla',
  color: 'Yellow',
  engine: {
    Displacement: 2.0,
    cylinders: 4,
  },
  license_plate: 'ASSF4287',
};

const display = ({
  maker,
  model,
  color = 'unknown',
  engine: { size, cilinders },
  license_plate = 'unknown',
  ...otherProperties
}) => {
  console.log('Maker & Model: ' + maker + ' ' + model);
  console.log('Color: ' + color);
  console.log('Engine: ' + size + 'L ' + cyliners + 'CL');
  console.log('License Plate: ' + license_plate);
};

display(car);

display(car);
 /**
 * 'Maker & Model: Toyota Corolla'
 * 'Color Yellow'
 * 'Engine: 2L 4CL'
 * 'License Plate: ASSF4287'
 **/

Conclusion

The use of destructuring syntax helps us write clear and simple code even when using complicated data structures. This is some information and examples about what you can do with destructuring in JavaScript ES6 but if you want to increase your knowledge about this subject visit MDN for more information.

Happy Coding!!!