JavaScript

Implode an Array With JavaScript?

In computer programming, the term “implode” refers to a function that merges/combines elements of an array into a single string. In PHP, there is an “implode()” method for doing this, but in JavaScript, there is no built-in method for combining array elements in a single string. But, it provides some alternatives to performing this task.

This blog will define the procedure to implode an array using JavaScript.

How to Implode an Array With JavaScript?

To implode an array, utilize the following methods:

Method 1: Implode an Array Using “join()” Method

Use the “join()” method to implode an array. This method takes an array and outputs a string containing all of the array’s elements concatenated together, with an optional separator between them. The separator is specified as an argument to the join() method.

Syntax

Follow the given syntax to implode the array elements in JavaScript:

array.join()

Example

Create an array named “array”:

var array =["Java", "Script"];

Invoke the “join()” method without passing any separator and store the resultant string in the variable “string”:

var string = array.join();

Finally, print the imploded array on the console:

console.log(string);

The output indicates that without specifying any separator, the “join()” method prints a comma-separated string:

If you want to implode the array as a single string without any separator, pass the empty string called separator as an argument:

var separator = '';
var string = array.join(separator);

Now, print the string on the console:

console.log(string);

As you can see that the array elements have been successfully imploded as a single string:

Method 2: Implode an Array Using “for” Loop

You can also implode an array using the traditional “for” loop. It iterates an array and concatenates the elements in a single array.

Example

Create a variable “temp” that stores an empty array as a separator:

var temp = '';

Use the “for” loop to iterate the array until its length and add the elements in a variable “temp”:

for(var i=0; i<array.length;i++){
 temp += array[i];
}

Lastly, print the temp in the console that stores a concatenated array elements as a string:

console.log(temp);

Output

We have provided all the necessary instructions relevant to the imploding of an array in JavaScript.

Conclusion

Imploding an array means merging/combining array elements in a string. To implode an array in JavaScript, utilize the “join()” method, or the “for” loop. This blog defined the procedure to implode an array using JavaScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.