libri-javascript-python

In this lesson we introduce the JavaScript join method which, given an array, returns a string.

This method is similar to the previous toString, discussed in the previous lesson. The difference with the toString method is that the latter can also be used on other variables, while join is used only with arrays.

Also in this case the original array remains unchanged, so we have to store the result in another variable, and then use it where appropriate.

The syntax of the JavaScript join() method is as follows: array.join(separator), where the separator is optional and if not specified, elements will be separated by a comma (,).

Let’s now deal with practical examples to understand how it works.

JavaScript join – example 1

As a first example let’s convert a simple array of numbers into a string, using the join () method.

So let’s assume we have the following array of numbers:



var numbers = [5,4,3,2,6,9,62];

We then use the join method to convert the array and store the result in a variable, such as a string name.

Then we display the result in the browser console.



var str = numbers.join();
console.log(str);

In this way we will get numbers separated by a comma.

JavaScript join – example 2

We propose the same example again but with an array of strings, so we repeat the example above by changing only the array.

For example, if by hypothesis we have the following array:



var objectsSchools = ['pencil', 'eraser', 'sharpener', 'notebook', 'pencil'];

And then we apply the join method to the array of starting strings, displaying the result for simplicity always in the browser console.



var str = objectsSchools.join('-');
console.log(str);

We will display the following result: pencil – eraser – sharpener – notebook – pencil.

Conclusion

In this article we talked about the JavaScript join method, in the next lessons we will cover other methods with numerous other examples.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript