JavaScript Arrays: Join
Welcome to the Join lesson!
The JavaScript array "join" method combines an array's elements into a single string. We can customize the separator used between the array elements.
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
Sometimes we want to turn an array of strings into a single string. We can
.jointhem together.>
['a', 'b', 'c'].join('');Result:
>
['Amir', 'Betty'].join('');Result:
'AmirBetty'
.jointakes one argument: the string to put between each array element, called the "separator". If we call it without an argument, the strings are joined with','by default.>
['Amir', 'Betty'].join();Result:
'Amir,Betty'
The separator can be any string.
>
['a', 'b', 'c'].join('x');Result:
'axbxc'
>
['a', 'b', 'c'].join('AND');Result:
'aANDbANDc'
If we join some empty strings together, we get a string of only commas. You can think about it as: the string has all of the commas in the original array.
>
['', ''].join();Result:
>
['', '', ''].join();Result:
',,'
>
['a', '', 'b'].join();Result:
'a,,b'
If we try to join an array that includes number or boolean elements, JavaScript converts them to strings.
>
[1, 2, 3].join('-');Result:
>
[true, 3, false].join('.');Result:
>
['w', 'd', 40].join('-');Result:
'w-d-40'
The same thing happens if we use a number or boolean as the separator. (You'll probably never do this intentionally, but you may do it accidentally!)
>
['a', 'b', 'c'].join(1);Result:
>
[4, 5].join(false);Result:
>
[1, 2, 3].join(4);Result:
'14243'
nullandundefinedbecome empty strings when.joined.>
[null, undefined].join();Result:
','
>
['a', null, undefined, 'b'].join();Result:
'a,,,b'
.joincomes up in many different situations. For example, we can use it to build a large string using short lines of code.>
function userTag(name) {return ['<User name="',name,'">'].join('');}userTag('Amir');Result:
'<User name="Amir">'
We can also
.jointo turn an array of words into a readable sentence.>
const foods = ['peas', 'carrots', 'potatoes'];foods.slice(0, -1);Result:
>
const foods = ['peas', 'carrots', 'potatoes'];const joined = [foods.slice(0, -1).join(', '),', and ',foods[foods.length - 1],].join('');joined;Result:
'peas, carrots, and potatoes'