Mico Gongob Hacker Noon profile picture

This article will cover the spread operator and how you can use them in your day-to-day JavaScript programming. This article assumes you have some familiarity with coding in the JavaScript ecosystem.


We will be using a code example from a previous post – How to Use Rest Parameters in JavaScript. Since the spread operator does the opposite thing of what rest parameters do, a good understanding of rest parameters would be helpful here. However, as a brief introduction, using the three periods syntax (…), rest parameters allow us to capture an indefinite number of function arguments as an array. It is kind of similar to Java Varargs or C# parameter arrays.

In this code example, the log function takes the level and args parameters then outputs them to the console.

// ------------------ 👇 a rest parameter
function log(level, ...args) {
  for (var i = 0; i < args.length; i++) {
    console.log(level, `{$i}`, args[i]);

The Spread Operator or Spread Syntax

Basically, the spread operator converts an array to a list of comma-separated values (CSV), contrasting rest parameters, where it takes a CSV and converts it into an array.

We have below a logging function similar to the one above (but without using rest parameters). Let us assume that the responseBody variable value comes from an external API that returns a list with varying types and values, and we want to log each element to the console. We can see from the output that while the function is expecting four arguments, we’ve only given it two. Hence the undefined being shown twice for variables arg2 and arg3.

function log(level, arg1, arg2, arg3) {
  console.log(level, '{0}', arg1);
  console.log(level, '{1}', arg2);
  console.log(level, '{2}', arg3);

var responseBody = [
  {name: 'Non-Master Anakin Skywalker'},

log('DEBUG', responseBody);
// expected output:
// DEBUG {0} [ { name: 'Non-Master Anakin Skywalker' }, 1, false ]
// DEBUG {1} undefined
// DEBUG {2} undefined

This can be resolved by providing the correct arguments to the function. This can be done by getting each element by index and pass each to the function.

log('DEBUG', responseBody[0], responseBody[1], responseBody[2]);
// expected output:
// DEBUG {0} { name: 'Non-Master Anakin Skywalker' }
// DEBUG {1} 1
// DEBUG {2} false

That should be good, our logging function is working as expected, but this can be improved. The desired output can be done with less code using the spread…

Continue reading: