Spread Operator Applied to Strings in JavaScript

The spread operator () can be used to get an array of characters easily from a string in ES6 and higher JavaScript.

The following code shows how this works:

const str = "hello"

const chars = [...str]

console.log(chars)

The result is:

[ 'h', 'e', 'l', 'l', 'o' ]

 

Interestingly, we can also use the spread the inside an object instead of an array, in which case the operator will assign the characters of the string at each index from 0 to the length of the string minus one, using the indexes as keys in the object. The example below shows this.

const str = "hello"

const arr = { ...str }

console.log(arr)

Result:

{ 
  '0': 'h', 
  '1': 'e', 
  '2': 'l', 
  '3': 'l', 
  '4': 'o' 
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *