How to append something to an array?

How do I append an object (such as a string or number) to an array in JavaScript?

Text Copied From stackoverflow.com
on : Tue, Dec 09, 2008 Views : 2023435

Accepted Answer

Use the push() function to append to an array:



// initialize array var arr = [
  Hi,
  Hello,
  Bonjour ];
  
// append new value to the array arr.push(Hola);
  console.log(arr);

Will print

[Hi, Hello, Bonjour, Hola] 

You can use the push() function to append more than one value to an array in a single call:



// initialize array var arr = [ Hi, Hello, Bonjour, Hola ];
  
// append multiple values to the array arr.push(Salut, Hey);
  
// display all values for (var i = 0;
 i < arr.length;
 i++) 
{

  console.log(arr[i]);
 
}

Will print

Hi Hello Bonjour Hola  Salut Hey 

Update

If you want to add the items of one array to another array, you can use firstArray.concat(secondArray):

var arr = [
  apple,
  banana,
  cherry ];
  arr = arr.concat([
  dragonfruit,
  elderberry,
  fig ]);
  console.log(arr);

Will print

[apple, banana, cherry, dragonfruit, elderberry, fig] 
Text Copied From stackoverflow.com
on : Tue, Dec 09, 2008

Ask Question

If you want to ask question you must LogIn or SignUp
Login SignUp

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp