Spread operator for strings

11,009

Solution 1

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(''));

Solution 2

Math.max on an empty string evaluates like +" " or Number(" ") therefore 0

let num = "1 2 3";

console.log( Math.max(...num))  // ["1"," ","2"," ","3"] >>> [1,0,2,0,3] >>> 3

therefore it's not wise to spread directly a string with numbers, cause 34 8 9 will max to 9.
Always split by your separator num.split(" ") beforehand.

Solution 3

var x = "123";
console.log(Math.max(...x));

// prints 3

... treats the string as an iterable, equivalent to an array with one character mapped to one element.

Solution 4

Spread syntax will result in 5 elements, where 2 of them are space characters:

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

//=> ["1", "", "2", "", "3"]


In detail:

The result of the spread operator will be ["1", "", "2", "", "3"] containing the space characters.

Acting on this result, Math.max() will try and find the biggest number in the array, by converting non-Number types to Number, similar to running Number("1") to convert a String into a Number. The space characters are converted into a Number 0, similar to Number("") === 0.

So, you're left with the following list of numbers: [ 1, 0, 2, 0, 3 ] upon which Math.max() will pick 3 as the biggest number of all.

Share:
11,009
Moaaz Bhnas
Author by

Moaaz Bhnas

Updated on July 13, 2022

Comments

  • Moaaz Bhnas
    Moaaz Bhnas almost 2 years

    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.

    var x = "1 2 3";
    console.log(Math.max(...x));