Do you know the difference between toString() and join() methods? – Javascript array methods

Hey there coders! What’s up.

If you are a bit confused about javascript array toString() and join() methods then read this post till the last word and soon you will know the difference between javascript toString() and join() methods. So, let’s begin.

So first see what the toString() method does when used with the array.

When we use JavaScript toString() method on an array then it converts the array to a string of array values.

Let’s see it with an example.

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript toString() Method</h1> 

<p id="demoId"></p>

<script>
const cars = ["Porsche", "BMW", "Audi", "Jaguar"];
document.getElementById("demoId").innerHTML = cars.toString();
</script>

</body>
</html>

Output :

JavaScript toString() Method

Porsche,BMW,Audi,Jaguar

In this example, the toString() method is converting the cars array to a string of comma-separated array values. That means the cars array has 3 strings but the output is a single string (Porsche to Jaguar including commas).

Now let’s see join() method.

Javascript join method also do the same but the difference is that you can specify the seperator while using join() method.

Let’s see it with an example.

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript join() Method</h1> 

<p id="demoId"></p>

<script>
const cars = ["Porsche", "BMW", "Audi", "Jaguar"];
document.getElementById("demoId").innerHTML = cars.join(" - ");
</script>

</body>
</html>

Output :

JavaScript join() Method

Porsche – BMW – Audi – Jaguar

In this example, you can see that like toString() method join() method has also joined all array elements into a string but notice the hyphen(-) in the output. I have passed hyphen(-) as a parameter to the join() method. Now the output has hyphen instead of comma. And that’s the difference. You can specify the separator here.

Now you know the difference between javascript toString() and join() methods.

Goodbye.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: