Family Magazine

The Spread Operator in JavaScript (explained in Cockney)

By Geoff Griffiths @mmatraining1980

TLDR; – The Spread operator allows you to join strings or arrays together in one longer string or array

The Spread Operator in JavaScript (explained in cockney)

Image from Reddit

Good tutorial here

Right, guv’nor! Picture this. You’ve got yourself a box of LEGOs, like? Now in the world of JavaScript, this box is what we’d call an array. It’s a list of things, sorted and lined up all proper like.

Now, suppose you have another bigger box, crammed full of all sorts of knick-knacks. You fancy bunging your LEGOs in there, but not as a separate box. Nah, you want to spread ’em out so each LEGO is jumbled up with the other toys.

This is what the JavaScript spread operator is all about. It’s like taking your box of LEGOs and tipping ’em into the larger toy box.

Here’s a little squiz:

let legos = ['red', 'blue', 'green'];
let otherToys = ['doll', 'car', ...legos, 'ball'];

console.log(otherToys); 
// Output: ['doll', 'car', 'red', 'blue', 'green', 'ball']

In this case, ...legos is using the spread operator. It’s like we’re tipping out all the LEGO pieces (each colour) into the otherToys array. Job’s a good ‘un!

So the spread operator ... in JavaScript is like spilling the beans, it pulls all elements from an array (or all properties from an object), and scatters them into something else.

And remember, this operator doesn’t muck about with the original array (or your LEGO box). It’s like taking the LEGO pieces out for a bit of a lark. The original LEGO box is still there, untouched. Bob’s your uncle, Fanny’s your aunt!

Here are some other notes I’ve robbed from other websites (with references back to um tho)

Programiz.com

Spread Operator

The spread operator ... is used to expand or spread an iterable or an array. For example,

const arrValue = [‘My’, ‘name’, ‘is’, ‘Jack’];

console.log(arrValue); // [“My”, “name”, “is”, “Jack”]
console.log(…arrValue); // My name is Jack

In this case, the code:

console.log(...arrValue)

is equivalent to:

console.log('My', 'name', 'is', 'Jack')

Copy Array Using Spread Operator

You can also use the spread syntax ... to copy the items into a single array. For example,

const arr1 = ['one', 'two'];
const arr2 = [...arr1, 'three', 'four', 'five'];

console.log(arr2); 
//  Output:
//  ["one", "two", "three", "four", "five"]

You can run the code in the programiz code runner thing here

codingsumit

The Spread Operator in JavaScript (explained in cockney)

Back to Featured Articles on Logo Paperblog