Spread operator for strings

Moaaz Bhnas picture Moaaz Bhnas · Jan 7, 2018 · Viewed 8.3k times · Source

I read about spread syntax on MDN and that it can be used with both arrays and strings:

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) are expected - mdn.

It's clear for me with arrays. It will expand the elements as separate arguments.
But I didn't find examples for strings.

So, what are the rules to use spread syntax to expand a string in a function call?
Should the string characters be separated with spaces cause I tried this and it printed 3.

Answer

Olian04 picture Olian04 · Jan 7, 2018

As we can see below, your example is actually spreading to 5 elements, where 2 of them are space characters. You can also see below that the spread operator on a string seems to be the same as using .split('').

const x = "1 2 3";
console.log([...x]);

console.log(x.split(''));