Breaking into letters with the spread operator!

I was messing around with the spread operator, and I wanted to share this little trick:

var word = "dinosaurs";

// old-school
var letters = word.split('');
console.log(letters);

// new-school with the spread operator
var letters2 = [...word];
console.log(letters2);

You can use the spread operator across a variety of similar scenarios like with arrays or object propertiesā€¦sort of :wink:

Cheers,
Kirupa

1 Like

Object properties spread just fine :sunglasses:

var word = {
  start: 'dino',
  end: 'saurs',
};

console.log({ ...word }); // {start: 'dino', end: 'saurs'}

Itā€™s a different kind of spread, an object spread vs. an array spread, but array spreading only works on iterables - values that implement [Symbol.iterator]. String is such an object, in fact the only primitive that does so. Object spread works on any value spreading own, enumerable properties into the new literal - and, in the case of strings, given that it is also array like beyond implementing [Symbol.iterator] (indices referring to characters, e.g. 'dinosaurs'[0] === 'd'), its characters:

var word = 'dinosaurs';
console.log({ ...word });
// {0: "d", 1: "i", 2: "n", 3: "o", 4: "s", 5: "a", 6: "u", 7: "r", 8: "s"}

Other objects can also be blessed with array spreading capabilities if they also implement a [Symbol.iterator]. An easy way to do this for generic use cases is using Object.values along with Array.prototype.values (confusingly enough, Object static variations [values, keys, entries] return arrays while Array instance methods return array iterators, which is what is needed for [Symbol.iterator]).

var word = {
  start: 'dino',
  end: 'saurs',
  [Symbol.iterator]: () => Object.values(word).values(),
};

console.log([ ...word ]); // ['dino', 'saurs']

Note that for function argument spreading, array spread is used because arguments are an unnamed, ordered list of values.

2 Likes