JAVASCRIPT SPREAD OPERATOR SIMPLIFIED

You will agree with me that ES6(ECMA SCRIPT 2015) came with lots of goodies for developers, one of which is our topic of discussion today, "The spread operator" In this article, we will look into what spread operator is, use cases with examples. By the end of this article, you will be fully armed with various ways of using the spread operator for cleaner and more readable codes.

Alright, come with me as we ride together to understand what spread operator is and how it's been used in javascript. A quick note that the spread operator has a twin called The Rest Parameter though opposite in action. The rest parameter is used as a parameter on functions and collects items into a single array, while the spread operator is used as an argument. They are both denoted with three dots{...} followed by a variable name {...ages}.

  • WHAT IS SPREAD OPERATOR.

The spread operator also referred to as the three magic dots{...} is majorly used to spread out the content of an iterable i.e string, array, or objects, and thus returns a new variable.

Note that throughout this article I shall refer to the spread operator with the {...}

  • USE CASES AND EXAMPLES

Now let look at the uses of the spread operator with examples.

  • It is used in javascript Math functions.

  • It is used to combine arrays into a single array.

  • It is used to copy an array/object into another.

  • It is used to add items to an array.

  • It is used to convert a string into separate characters.

Using a Math function. Math functions work well on numbers and strings. But with an array, it doesn't work the same let get this clearer with an example of each case.

let minNum = Math.min(2, 3, 4, 5, 60, 1);
     console.log(minNum);
// 1

The example above works perfectly because the function expected a numeric argument, which is what is been passed. Now let see a case of an array;

let ages = [23, 24, 30, 16, 8, 12, 4];
let minAge =  Math.min(ages); 
console.log(minAge);
// NAN

// This throws an error(NAN) because the function sees the ages array as a value and the ages passed into the function as a single argument. To prevent the error, {...} comes in handy.

let ages = [23, 24, 30, 16, 8, 12, 4];
let minAge =  Math.min(...ages); 
console.log(minAge);
// 4;
// Same goes for Math.max()
let ages = [23, 24, 30, 16, 8, 12, 4];
let maxAge =  Math.max(...ages); 
console.log(maxAge);
//30;

With {...} values are spread open as a list of items and thus calling the function iterate through the array to return an appropriate value.

Combining arrays. Yes, this can be done without using the spread operator as we shall see below, but for readability, cleanliness, and ease of manipulating data, the spread operator is best suited.

Combining array without the {...} returns a nested array which in most cases not what we want. So to solve this the service of {...} is employ as shown below.

Example combining without {...}

let age1 = [12, 9, 6, 14, 8];
let age2 = [30, 22, 28, 21];
let age = [age1, age2] 
console.log(age);
//
[ [ 12, 9, 6, 14, 8 ], [ 30, 22, 28, 21 ] ]

Now let see an example with {...} Javascript {...} helps to combine all the items into a single array which is achieved by adding 3dots before the variable name.

let age1 = [12, 9, 6, 14, 8];
let age2 = [30, 22, 28, 21];
let ages = [...age1, ...age2];
console.log(ages);
// [
  12,  9,  6, 14, 8,
  30, 22, 28, 21 
]

Adding items to an array. Adding items to array; yes it will come to mind that why {...} when this can be done with either push() or unshift(). Note that unshift adds an item to the beginning of the array while push adds an item to the end of an array. With {...} items can be added to any part of an array.

Example of using {...} to add items to an array.

let age1 = [12, 9, 6, 14, 8];
let age2 = [...age1, 20,30]
console.log(age2);
// result 
[ 12,  9,  6, 14, 8, 20, 30]
// this output a single array with all the items

Note that with {...} items are added at any index of the array as shown below.

let age1 = [12, 9, 6, 14, 8];
let age2 = [30, 22, 28, 21];
let ages = [ 30, 10, ...age1, 30, 90, ...age2, 50]
console.log(ages);
// result  [30, 10, 12,  9,  6, 14,
   8, 30, 90, 30, 22, 28,
  21, 50]

Copy and array to another array; Copying an array into another is a common cause in working with arrays/objects, this may be done using an array method slice() or by referencing an array to another as shown below.

let name = ['Som', 'Jamal', 'Khan', 'Shan']
let names = name;
console.log(name);
console.log(names);
// [ 'Som', 'Jamal', 'Khan', 'Shan' ]
[ 'Som', 'Jamal', 'Khan', 'Shan' ]

from the example above you will observe that arrays are perfectly copied, so why the need for {...}? Yes, the need for a spread operator becomes inevitable when either of the arrays is to be modified/mutated. If either of the variables above is mutated it affects both values which may not be the suitable case most of the time.

name.push('Umar')
console.log(name);
console.log(names);
// [ 'Som', 'Jamal', 'Khan', 'Shan', 'Umar' ]
[ 'Som', 'Jamal', 'Khan', 'Shan', 'Umar' ]

both of these will output the same value because the name variable was copied to the names variable using the assignment operator which reference the values of name to names. This can be avoided using the magic dots {...}. Assigning name variable to names with the magic dots {...} will copy the content of name to names but will prevent mutation of one value affecting the other, let see from the example below.

let name = ['Som', 'jamal', 'Khan', 'Shan']
let names = name;
names.push('Mike')
console.log(name);
console.log(...names);
// [ 'Som', 'Jamal', 'Khan', 'Shan' ]
[ 'Som', 'Jamal', 'Khan', 'Shan', 'Mike']

From the result above only the names variable is being mutated the original value is never affected. this is one of the powers {...} provides.

Copy, Modifies or Merge object literal. The spread operator works well on objects literal to either copy an existing object into another, update an object or modify a property with another. Let see how it works from the example below.

let boss1 =
 {
    name: 'Malven',
    location: 'Newcastle',
    position: 'CTO', 
    likes: 'Karyaking',
  }
let boss2 = {...boss1};
console.log(boss2);
//  {
  name: 'Malven',
  location: 'Newcastle',
  position: 'CTO',
  likes: 'Karyaking'
}

here we have successfully copied boss1 properties into the boss2 object. {...} can also be used to combine or merge 2 objects. Note that in using {...} to merge objects of the same property name the latter takes precedence over the former. Let's see that in action.

let student = {
name: 'Ann Umar',
age: 12,
location: 'Spain',
}

let teacher = {
 title: 'Ms',
hobby: 'Reading',
location: 'Uk', 
}
let member = {...student, ...teacher}
console.log(member);
// {
  name: 'Ann Umar',
  age: 12,
  location: Uk',
  title: 'Ms',
  hobby: 'Reading'
}

From the code snippet above you will observe that the content of the student object has been merge with that of the teacher, and the location property has been modified because they both have the same property in which the later variable is favored.

Javascript {...} Is use to spread a string into separate characters. See the example below.

let str = 'Spread operator';
let strChar = [...str]
console.log(strChar);
// ['S', 'p', 'r', 'e',
  'a', 'd', ' ', 'o',
  'p', 'e', 'r', 'a',
  't', 'o', 'r']

From the examples above I have shown how the spread operator is used in various cases, such as copying an array into another, combining arrays, adding items to an array... The magic 3dots{...} is easy to use, gives a more readable and cleaner code.

please give feedback/comments. Thank you!!!