×

Index

JavaScript Tutorial

JavaScript Examples

CSS Tutorial

CSS Examples

JavaScript: How to append something to an array?

Learn how to append something to an array in JavaScript?
Submitted by Pratishtha Saxena, on April 30, 2022

How to append something to an array using JavaScript?

In JavaScript there are various ways to append something to an array or to append two arrays.

  1. Using push() method
    array_1.push('121','John')
  2. Using spread operator
    var array_3 = [...array_1,...array_2] 
  3. Using concat() method
    var array_3 =array_1.concat(array_2)

There can be many more ways to do so but these are some most common and easy ways to append something to an array. Let's see how.

Example 1

var array = ['Dog', 'Cat', '526']
array.push('121', 'John') // using push
console.log(array)

Output:

(5) ['Dog', 'Cat', '526', '121', 'John']

Example 2

var array_1 = ["Birds", "Fishes"]
var array_2 = ["Animals", "Dinosaurs"]

// using spread operator
var array_3 = [...array_1, ...array_2]

console.log(array_3)

Output:

(4) ['Birds', 'Fishes', 'Animals', 'Dinosaurs']

Example 3

var states = ["MP", "UP", "Gujrat", "Rajasthan"]
var unionTerritory = ["Puducherry", "Chandigarh", "Andaman & Nicobar Island", "Lakshadweep"]

// using concat
var India = states.concat(unionTerritory)

console.log(India)

Output:

(8) ['MP', 'UP', 'Gujrat', 'Rajasthan', 'Puducherry', 'Chandigarh', 'Andaman & Nicobar Island', 'Lakshadweep']

JavaScript Examples »



Related Examples



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.