jskatas.org Continuously Learn JavaScript. Your Way.

Spread operator: with strings

Spread syntax in use with strings.

Spread syntax with strings

expands each character of a string by prefixing it with ...
const [b, a] = [...'ab']; assert.equal(a, 'a'); assert.equal(b, 'b');
expands any kind of character
const arr = [...'12']; assert.deepEqual(arr, ['1', ' ', '☒', ' ', '2']);
works anywhere inside an array (must not be last)
const letters = ['a', 'bcd', 'e', 'f']; assert.equal(letters.length, 6);
don`t confuse with the rest operator
const [...rest] = ['1234', ...'5']; assert.deepEqual(rest, ['1', '2', '3', '4', '5']);
can also be used as function parameter
const max = Math.max('12345'); assert.deepEqual(max, 5);

Links

Syntax docs on MDN.

Required Knowledge

Related Katas

Unary Operators

Bitwise Shift Operators

Rest operator

Spread operator

Difficulty Level

INTERMEDIATE

First Published

13 April 2015

Stats

5 tests to solve