Reputation: 1170
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));
Upvotes: 9
Views: 22254
Reputation: 206048
Math.max on an empty string evaluates on empty string like +" "
or Number(" ")
therefore 0
const str = "1 2 3";
console.log( Math.max(...str)) // ["1"," ","2"," ","3"] >>> [1,0,2,0,3] >>> 3
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(/ +/)
(one-or-more spaces) beforehand:
const str = "1 34 9 2";
// Issue:
console.log( Math.max(...str) ) // 9 since [1,0,3,4,0,9,0,2]
// Fix:
console.log( Math.max(...str.split(/ +/)) ) // 34
Upvotes: 5
Reputation: 5412
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.
Upvotes: 1
Reputation: 5303
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.
Upvotes: 2
Reputation: 6872
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(''));
Upvotes: 9