How does this code break the string into parts?

2

Through this question: How to remove all element from array except the first one in javascript .

I've adapted the code for my need.

var rua = 'RUA NILO PEÇANHA';
const head = ([x, ...xs]) => x
const tail = ([x, ...xs]) => xs
console.log('${head(rua).toUpperCase()}${tail(rua).join('').toLowerCase()}')

I ended up choosing the code that has the two covenants head and tail .

I've never seen anything like: ([x, ...xs]) => x . I know that Spread is being used together with arrow functions ( arrow functions ).

Doubt:

  • How did a code like ([x, ...xs]) => x return only the first letter and ([x, ...xs]) => xs returned all the rest?
asked by anonymous 02.10.2018 / 22:27

1 answer

9

The functions head and tail make a "smart" use of the spread operator and the fact that strings allow character character access with the use of brackets.

When it is declared that the argument is [x, ...xs] , we are saying that the function receives an array. When we pass a string, it is treated as an array of characters.

For example, if we call head passing abcd :

head("abcd")

What the function receives internally is:

["a", ["b", "c", "d"]]

The first position of the array, x , is the first character. The rest will be stored in the second position of the array, which in turn is another array, xs . Note that in your code there is .join('') in tail result. This is because tail returns array, which must be converted to string by join so that the toUpperCase method can be called next, since it only applies to strings.

    
02.10.2018 / 22:47