Skip to main content

How to Insert an Element Into an Array in JavaScript?

Published: Asked By 1 Answers Answered

Learn how to insert an element into an array in JavaScript. Explore methods like push(), unshift(), splice(), and examples for adding elements at any position efficiently.

Share:

4 Answers

S
Sooraj Community Contributor Answered on

In JavaScript, you can use the push() method to add an element to the end of an array. Here’s how it works:

  1. First, create an array (let’s call it fruits):

    JavaScript

     

    const fruits = ["Banana", "Orange", "Apple", "Mango"];
    
    
  2. To add a new item (let’s say “Kiwi”) to the end of the array, use the push() method:

    JavaScript

    fruits.push("Kiwi");

     

  3. If you want to add multiple items (for example, “Kiwi” and “Lemon”), you can pass them as separate arguments to push():

    JavaScript

    fruits.push("Kiwi", "Lemon");

  4. The push() method modifies the original array and returns the new length of the array.

So, in summary:

  • To add an element to the end of an array: array.push(item1, item2, ..., itemX)

Remember that push() is a handy way to dynamically update arrays in JavaScript.

L
LAZIO LEO Community Contributor Answered on

It can be done using push()  methOD 

let arrayin=[1,2,3,4];

arrayin.push(5);

output:1,2,3,4,5

J
joshijosejose2197@gmail.com Community Contributor Answered on

To push an element to an array in JavaScript, we can use the push() method. The push() method adds one or more elements to the end of an array and returns the new length of the array.

Example : 

const numbers = [1, 2, 3];
numbers.push(4);
console.log(numbers); // Output: [1, 2, 3, 4]

numbers.push(5, 6);
console.log(numbers); // Output: [1, 2, 3, 4, 5, 6]
S
Sahadha Community Contributor Answered on

let array =[ "A", "B", "C", "D"];

array. push ("E");

// output = A, B, C, D, E

Your Answer

Other Resources

Quiz Image
Quiz

Test your knowledge with interactive quizzes.

Interview Questions Image
Interview Questions

Prepare for interviews with curated question sets.

Q&A Image
Q&A

Ask your coding-related doubts and get answers.

Certification Image
Certification

Earn certifications to enhance your resume.

internships Image
Internships

Hands-on projects to improve your skills.

Quiz Image
Quiz

Test your knowledge with interactive quizzes.

Interview Questions Image
Interview Questions

Prepare for interviews with curated question sets.

blog Image
Blogs

Add your technical blogs and read technical topics.

Certification Image
Certifications

Earn certifications to enhance your resume.