JavaScript Basic Array Methods

JavascriptFront End TechnologyObject Oriented Programming

Some basic JavaScript array methods are −

MethodDescription
Array.push()To add elements to the end of the array.
Array.pop()To remove elements from the end of the array.
Array.unshift()To add elements to the front of the array
Array.shift()To remove elements from the front of the array.
Array.splice()To add or remove elements from the splice

Following is the code for the basic array methods −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
   font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.sample,
.result {
   font-size: 18px;
   font-weight: 500;
   color: red;
}
.result {
   color: blueviolet;
}
</style>
</head>
<body>
<h1>JavaScript Basic array methods</h1>
<div class="sample">arr =</div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to apply the array methods on the above array</h3>
<script>
let resultEle = document.querySelector(".result");
let sampleEle = document.querySelector(".sample");
let arr = ["A", "B", 1, 2, 3, 5];
sampleEle.innerHTML += arr;
document.querySelector(".Btn").addEventListener("click", () => {
   arr.pop();
   resultEle.innerHTML += "arr.pop() = " + arr + "<br>";
   arr.push(22);
   resultEle.innerHTML += "arr.push(22) = " + arr + "<br>";
   arr.shift();
   resultEle.innerHTML += "arr.shift() = " + arr + "<br>";
   arr.unshift();
   resultEle.innerHTML += "arr.unshift(55) = " + arr + "<br>";
   arr.splice(3, 0, "D", "E", "F");
   resultEle.innerHTML += 'Array.splice(3,0,"D","E","F") = ' + arr;
});
</script>
</body>
</html>

Output

On clicking the ‘CLICK HERE’ button −

raja
Published on 06-May-2020 12:03:49
Advertisements