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
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:
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
Creating engaging and entertaining content for designers and developers since 1998.