Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spread operator for strings

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));
like image 528
Moaaz Bhnas Avatar asked Jan 07 '18 18:01

Moaaz Bhnas


2 Answers

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(''));
like image 165
Olian04 Avatar answered Sep 18 '22 08:09

Olian04


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.

like image 20
Roko C. Buljan Avatar answered Sep 19 '22 08:09

Roko C. Buljan