javascript
  1. javascript-concat

JavaScript concat() Method

The concat() method is a built-in function in JavaScript that is used to merge two or more arrays or strings, and return the merged result as a new array or string.

Syntax

The syntax for using the concat() method is:

array1.concat(array2, ..., arrayn)

Here, array1 is the array to which the other arrays or strings will be concatenated. The array2 to arrayn are optional and are the arrays or strings to be concatenated.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Array Concatenation Example</title>
</head>
<body>

<!-- Placeholder for displaying the output -->
<p id="output"></p>

<script>
    // Arrays
    var arr1 = ["apple", "banana"];
    var arr2 = ["orange", "mango"];

    // Concatenate arrays
    var result = arr1.concat(arr2);

    // Display the concatenated array
    document.getElementById("output").innerHTML += "Concatenated Array: " + result.join(', ');
</script>

</body>
</html>
Try Playground

In this example, the concat() method is used to merge arr1 and arr2 arrays into a new array called result.

Output

The concat() method returns a new array that contains the elements from the original arrays or strings that were concatenated.

Explanation

The concat() method does not change the original arrays. Instead, it creates a new array that contains all of the elements from the original arrays or strings in the order that they were concatenated.

The concat() method can be used to merge arrays or strings of any length. It can also be used to concatenate an array with a string, or two strings together.

Use

The concat() method is used to merge two or more arrays or strings into a single array or string. It is commonly used in web development to combine multiple arrays or strings into one, which makes processing and manipulating the data easier and more efficient.

Important Points

  • The concat() method does not modify the original arrays.
  • The new array or string generated by the concat() method can be assigned to a variable to be used later.
  • The concat() method can concatenate multiple arrays or strings at once.
  • It is also possible to use the spread operator (...) to concatenate arrays.

Summary

The concat() method is a useful function in JavaScript that is used to merge two or more arrays or strings into a new array or string. It is a non-destructive function that does not alter the original arrays or strings, and it is commonly used in web development to manipulate and process data. The concat() method is easy to use, and it can be used to concatenate arrays of any length or type.

Published on: