Home Courses Array Add Elements - push(), unshift(), splice() with Input Field

Array Add Elements - push(), unshift(), splice() with Input Field

Arrays are used everywhere in real projects. Whether it is a list of users, products, or students, you will always need to add new data. That’s why this topic is very important.


Add Element at the End

If you want to add an element at the last position of an array, you can use the push() method.


let users = ["anil", "sam", "sidhu"];

users.push("vinay");
console.log(users);

After running this, "vinay" will be added at the end of the array.


Add Element at the Beginning

If you want to add an element at the starting position, you can use the unshift() method.


let users = ["anil", "sam", "sidhu"];

users.unshift("tony");
console.log(users);

Now "tony" will be added at the beginning, and all other elements will shift forward.


Add Element at Any Position (Middle)

If you want to add an element at any specific position, you can use the splice() method.


let users = ["anil", "sam", "sidhu"];

users.splice(1, 0, "peter");
console.log(users);

Here, 1 is the position, 0 means no element will be deleted, and "peter" will be added at that position.


Add Element Using Input Field

Now let’s create a simple UI where the user can enter position and value, and the element will be added dynamically.


<html>
<head></head>

<body>
<h1>Add Item in Array</h1>

<span>Element Position</span>
<input type="text" id="position" placeholder="enter position">
<br><br>

<span>Element Value</span>
<input type="text" id="value" placeholder="enter value">
<br><br>

<button onclick="addElement()">Add Element</button>

<script>
let users = ["anil", "sam", "sidhu"];
console.log(users);

function addElement() {
let val = document.getElementById('value').value;
let pos = document.getElementById('position').value;

users.splice(pos, 0, val);
console.log(users);
}
</script>
</body>
</html>

When you enter a position and value and click the button, the new element will be added at that position.

If you enter a position that does not exist, JavaScript will add the element at the end.

Share this lesson: