Execute Program

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 .join them together.

  • >
    ['a', 'b', 'c'].join('');
    Result:
  • >
    ['Amir', 'Betty'].join('');
    Result:
    'AmirBetty'Pass Icon
  • .join takes 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'Pass Icon
  • The separator can be any string.

  • >
    ['a', 'b', 'c'].join('x');
    Result:
    'axbxc'Pass Icon
  • >
    ['a', 'b', 'c'].join('AND');
    Result:
    'aANDbANDc'Pass Icon
  • 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:
    ',,'Pass Icon
  • >
    ['a', '', 'b'].join();
    Result:
    'a,,b'Pass Icon
  • 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'Pass Icon
  • 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'Pass Icon
  • null and undefined become empty strings when .joined.

  • >
    [null, undefined].join();
    Result:
    ','Pass Icon
  • >
    ['a', null, undefined, 'b'].join();
    Result:
    'a,,,b'Pass Icon
  • .join comes 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">'Pass Icon
  • We can also .join to 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'Pass Icon