From String to Array to String
Tags: javascript, algorithms, beginners, programming
Published: 2021-04-23 20:38:40

## About Writers
Hello everyone! 
![Hello GIF](http://37.media.tumblr.com/1dee0c9e399b34cc10c12d04506d5f10/tumblr_n53cb0KpVC1smcbm7o1_500.gif)
This is Waverley and Megan! We are both tech enthusiasts and graduated from Flatiron School recently. Both of us enjoy writing blogs to help other programmers learn and we learn from writing as well (win-win!). This will be our first time writing blogs on dev.to and collaborating on a series with each other, and we are so excited to create content for you all! **Feedback is appreciated as we continue to navigate this process** 🙏 

When we first decided to collaborate we came up with a lot of topics to write about. However, as we are both currently in our job search and as bootcamp graduates, we wanted to work on something that will help us now and others in the future. Ultimately, we decided to have this series focus on data structures and algorithms, something we both feel is important to know but not exactly the easiest to understand. 

Also, check out our Medium blogs for more of our work:
- [Waverley](https://waverley-place.medium.com/)
- [Megan](https://meganslo.medium.com/)

--- 
## Intro <a name = "intro"></a>

Today, we are going to talk about converting array to string, and vice versa. This is one of the commonly seen strategies that is used when solving string-and-array-related coding questions. 

Before we get started, if you are interested in knowing array methods, here's [Everything JavaScript Arrays & Array Methods!](https://dev.to/wlcreate/everything-javascript-arrays-array-methods-14om) by Waverley; and for string methods, here's [When to Use these String Methods in JavaScript](https://dev.to/mehmehmehlol/when-to-use-these-string-methods-in-javascript-3m4h) by Megan.

---
## Table of Contents <a name="toc"></a>
  * [Intro](#intro)
  * [From Array to String](#array-to-string)
    * [toString()](#toString)
    * [join()](#join)
  * [From String to Array](#string-to-array)
    * [split()](#split)
    * [Array.from()](#array-from)
    * [Object.assign([], string)](#object-assign)
  * [Bonus](#bonus)
    * [Spread Operator](#spread-operator)
  * [Conclusion](#conclusion)
 
---
## From Array to String <a name="array-to-string"></a>

Something that we often need to do is convert an array to a string. Thankfully JavaScript has two built-in methods to accomplish this: `toString()` and `join()`.

---
<a name="toString"></a> 
#### `toString()`: Returns a string representing the array and its elements (non-destructive) 

Like its name, the `toString()` method turns the array’s elements it was called on to a string. To be more specific, this method joins the array and returns one string containing each array element separated by commas.

*Fun fact*: JavaScript calls the toString method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation.

```javascript
const array1 = [1, 2, 'a', '1a'];
console.log(array1.toString());
// "1,2,a,1a"
```

---
<a name="join"></a>
#### `join()`: Join all the elements from an array to a string (non-destructive) 

`join()` creates and returns a string by concatenating, or joining, all of the elements of the array it was called on. By default the elements are separated by commas, however you can specify what you want to join/separate the elements by. On the other hand, if there is only one element in the array, the single item will be returned as a string without separators, and if there are no elements, an empty string is returned.

As mentioned, including an argument for the separator parameter is optional if you want the elements to be joined with a comma. Passing in an empty string as the argument will result in the elements joined without any characters/separators. 

Otherwise, the parameter is what you want to separate each pair of adjacent elements of the array for the returned string. If necessary, the separator is converted to a string.

```javascript
let joinArray = ['Wind', 'Water', 'Fire'];
joinArray.join();      // 'Wind,Water,Fire' b/c no separator so joined with commas and no spaces
joinArray.join(“, “);  // 'Wind, Water, Fire' b/c separator is comma and space
joinArray.join(“ + “); // 'Wind + Water + Fire' b/c separator is space, plus sign, space
joinArray.join(“”);    // 'WindWaterFire' b/c separator is an empty string
```

[Back to the Table of Contents](#toc)

---
## From String to Array <a name="string-to-array"></a>

#### `split()` <a name="split"></a>

As mentioned above, we can `join` string from array. We can also `split` string to array. Here, we are going to utilize the `join()` example to see the alternative results from above.
```javascript
let splitToArray = 'Wind, Water, Fire';
splitToArray.split('') 
/* [
     'W', 'i', 'n', 'd', ',',
     ' ', 'W', 'a', 't', 'e',
     'r', ',', ' ', 'F', 'i',
     'r', 'e'
   ], no separators
*/
splitToArray.split(' ') 
// [ 'Wind,', 'Water,', 'Fire' ], split by the whitespaces
splitToArray.split(',') 
// [ 'Wind', ' Water', ' Fire' ], split by commas
// As you can see there're still whitespaces in front of each element
// To solve this, we can do the following:
splitToArray.split(', ')
// [ 'Wind', 'Water', 'Fire' ], split by commas and one additional whitespace
```
This method is probably the most common way to split a string to an array and join afterwards.
 
Most of the time, when we want to apply array methods to a given string, this is a go-to method to do so. For instance, if we want to reverse a string:
```javascript
let example = 'JavaScript';

function reverse(str) {
  return str.split('').reverse().join('');
}

// In comparison to:
function reverse(str) {
  let reversed = '' // having to create a new string takes space
  for (let char of string) {
    reversed = char + reversed
  }
  return reversed;
}
```
Unless your interviewer specifies `reverse()` method is not allowed to be used, using the `split()` and `join()` method would help create a more readable, cleaner code. Also, since `reverse()` is not a string method, this is where we can utilize our array method in this case.

Palindrome is also another common question which you can make use of the `split()` and `join()`

---
#### `Array.from(string)` <a name="array-from"></a>

There are two ways you can use `Array.from()`. Either you want to modify and create a new shallow-copied array OR *drumroll please* 🥁🥁🥁 converting string to array.
```javascript
// To modify an array (Not the focus of this section)
Array.from([1, 2, 3, 4, 5], x => x * 2)
// [ 2, 4, 6, 8, 10 ]

// Convert string to array
Array.from('JavaScript')
['J', 'a', 'v', 'a', 'S', 'c', 'i', 'p', 't']
```

Remember, these are just some suggestive ways of converting string to array. 
According to this [article](https://blog.shovonhasan.com/never-use-array-from-to-convert-strings-to-arrays/), using the same reversed example we have above, the runtime of using `String.prototype.split()` is way faster than using `Array.from()`. 
But you know, at least we know `Array.from()` is one of the possible ways to convert string to array!

---
#### `Object.assign([], string)` <a name="object-assign"></a>

You probably heard of `Object.keys()`, `Object.entries()` which would return a new array. What about `Object.assign()`?
Similar deal! 
According to MDN, the definition of `Object.assign()` 
> The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.

`Object.assign()` takes two arguments: `target` and `source`. In our case, our `target` is an empty array `[]` and our `source` is the given string (which is an enumerable/ can be iterated object).
```javascript
const str = "foo";
Object.assign([], str) // ['f', 'o', 'o']
```
Yay! It works... on the surface... If you move this to TypeScript...

---
✋🏻PAUSE✋🏻
For those who are not familiar with TypeScript, don't worry. Here's a quick breakdown. You don't have to fully understand TypeScript. All you have to know is that TypeScript is a superset of JavaScript. Most of the time, variables are assigned to a primitive data type in advance.
```javascript
// In JS
const num = 1;

// In TS
const num : number = 1;
```
Cool thing about using TypeScript is that you would also see the variable type by hovering over the variable.

![Screenshot from CodeCademy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bxwuodfn7dzmy9yshmc0.png)
(Screenshot Credit: CodeCademy -- Learn TypeScript course)

Capiche? Hopefully you got the gist of it. Back to the topic...

---
If you move this to TypeScript, the type of this new copied array does not return as **an array of string**. 😱 
If we look at other methods we mentioned above:
```javascript
const str = 'foo';

const split = str.split('');
const from = Array.from(str);
```
Feel free to copy and paste the code to the [playground](https://www.typescriptlang.org/play/) and hover over `split` and `from`. 
They both return `split: string[]` and `from: string[]`. (`string[]` means array of strings.)

However, when you hover over `const obj = Object.assign([], str)`. It returns...
![Screenshot for Object.assign()](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4arulbcswlcpc2uuhkoc.png)

`obj : never[] & "foo"`, a.k.a. it is never an array but a string.

Isn't that interesting? 😮 (thanks to our [resource](https://www.samanthaming.com/tidbits/83-4-ways-to-convert-string-to-character-array/#a-caveat-about-object-assign-%E2%9A%A0%EF%B8%8F))

--- 

Although we have 3 ways to convert strings to array, including the spread operator (will be explained in the Bonus Section below), it seems like `split()` is the best way to do so!

[Back to the Table of Contents](#toc)

---
### Bonus <a name="bonus"></a>

#### Spread Operator <a name="spread-operator"></a>

While the spread operator (`...`)  is not specific to arrays, it is something helpful to know and use! 

From MDN, the spread operator: 
> allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

In other words, essentially the spread operator takes each of the elements inside of the passed in object or array and adds it to the array it is being added to. 

As a result, it is often used when all elements from an object or array need to be included in another list of some kind; typical use cases include copying arrays or concatenating an array to the end of an existing array. However, specifically for copying an array, the spread operator goes one level deep. Meaning that if you spread an array into another array, the array it was spread into will not be nested.

Furthermore, it’s important to know that you cannot spread objects into an array or an array into an object. This is because objects alone are not iterable. However, when used in an array or with iterating functions (such as `map` or `reduce`), they become iterable. 

Under the hood, when the merging occurs 2 objects together with the spread operator, it is assumed that another iterating function is used. On the other hand, if you spread a string into an array, it will create an array with each char in the string.

```javascript
// general example
let elements = [1, 2, 3]
let newElement = 4

let constructorArray = new Array(newElement, ...elements)
// [4, 1, 2, 3]

let literalArray = [new element, ...elements]
// [4, 1, 2, 3]

// copying an array- showing how the spread operator does not nest
let a = [[1], [2], [3]]
let b = [...a]

console.log(a) // [[1], [2], [3]]
console.log(b) // [[1], [2], [3]]

b.shift().shift()

console.log(a) // [[], [2], [3]]
console.log(b) // [[2], [3]]

// cannot spread an object into an array
let obj = {'key1': 'value1'}
let array = [...obj]; // TypeError: obj is not iterable

// spreading a string into an array
let test = [..."hello", ...“world”]
console.log(test) // ["h", "e", "l", "l", "o", "w", "o", "r", "l", "d"]
```
---
## Before You Go... <a name="conclusion"></a>

Let's conclude what we have discussed!

##### From Array to String, we have...
* `toString()`
* `join()`

##### From String to Array, we have... 
* `split()`
* `Assign.from()`
* `Object.assign([], string)`

Last but not least, spread operator (`...`) can be used to convert array to string, and vice versa. 

Hope you enjoy our first collab article and please give us feedback if you have!
![Thank You GIF](https://media.giphy.com/media/M9NbzZjAcxq9jS9LZJ/giphy.gif)

🙌🏻 Since we can't co-publish articles, we have to publish the same article in our own individual platform. Please give some shoutout to [Waverley](https://dev.to/wlcreate/all-about-javascript-arrays-array-methods-4ek4).

[Back to the Table of Contents](#toc)

---
## Resources:

- String <=> Array
  * [4 Ways to Convert String to Character Array in JavaScript](https://www.samanthaming.com/tidbits/83-4-ways-to-convert-string-to-character-array/)
 * [How to convert an Array to a String in JavaScript](https://flaviocopes.com/how-to-convert-array-to-string-javascript/)
- Array
  * [Everything JavaScript Arrays & Array Methods!](https://dev.to/wlcreate/all-about-javascript-arrays-array-methods-3n9) (by Waverley)
- String
  * [When to Use these String Methods in JavaScript](https://dev.to/mehmehmehlol/when-to-use-these-string-methods-in-javascript-3m4h) (by Megan)
- MDN