JavaScript concat Method Tutorial

The JavaScript concat() method is used to join two or more arrays, and returns a copy of the joined strings.

This script uses the concat() method to combine the elements of 2 or more arrays and creates another array in doing so.

Code Example
  1. function concatarray() {
  2. var chevCar = new Array ("Nova","Impala","Corvette");
  3. var fordCar = new Array ("Escort","Pinto","Taurus");
  4. var combCar = chevCar.concat(fordCar);
  5. document.getElementById('codebox').innerHTML = ("The variable <b>combCar</b> contains " + combCar);
  6. }

In this second tutorial demonstration we have stored all JavaScript Array Object Properties in one array, and all JavaScript Array Object Methods in another array.

To combine a copy of these arrays into one master array the concat() method would be used.

  1. var ArrayProperties = new Array("constructor", "length", "prototype");
  2. var ArrayObjectMethods = new Array("concat()", "join()", "pop()", "push()", "reverse()", "shift()", "slice()", "sort()", "splice()", "toString()", "unshift()", "valueOf()");
  3. var JavaScriptArray = ArrayProperties.concat(ArrayObjectMethods);

concat() and pop() exercise

Below is an interactive exercise of the above code. Press each button to display the values within a declared array, to display the values within a concatenated array (combination of more than one array) and the effects the pop() method has on the values in the array.

INTERACTIVE CORNER

 

 
What was popped?

Note: This method does not change the existing arrays, it merely makes copies, so you can repeat the pop() sequence by hitting the "concat() Array Values" button to literally refresh the array.