Array Methods
JavaScript provides built-in methods that make it easier to add, remove, search, and work with elements in an array.
What are Array Methods?
Array methods are built-in JavaScript functions that help us perform common operations on arrays.
Instead of writing the same logic manually, we can use methods such as push(), pop(), shift(), and unshift().
Why Do We Use Array Methods?
Array methods make array operations shorter, easier to understand, and easier to maintain.
Different methods are used for different tasks, such as adding elements, removing elements, searching for elements, or converting array data.
JavaScript array methods such as push(), pop(), unshift(), and shift() are used to add and remove elements from an array.
Common Array Methods
Add at the End
Adds one or more elements to the end of an array and returns the new array length.
Remove from the End
Removes the last element from an array and returns the removed element.
Remove from the Start
Removes the first element from an array and returns the removed element.
Add at the Start
Adds one or more elements to the beginning of an array and returns the new length.
How Array Methods Change an Array
The push() method adds a new element at the end of the array.
Example 1: push()
The push() method adds an element to the end of an array.
let courses = ["Java", "Python", "C#"];
courses.push("JavaScript");
console.log(courses);
Example 2: pop()
The pop() method removes the last element from an array.
let courses = ["Java", "Python", "C#", "JavaScript"];
let removedCourse = courses.pop();
console.log(removedCourse);
console.log(courses);
["Java", "Python", "C#"]
Example 3: shift()
The shift() method removes the first element from an array.
let students = ["Priya", "Amit", "Rahul"];
let firstStudent = students.shift();
console.log(firstStudent);
console.log(students);
["Amit", "Rahul"]
Example 4: unshift()
The unshift() method adds one or more elements to the beginning of an array.
let students = ["Amit", "Rahul"];
students.unshift("Priya");
console.log(students);
Summary
JavaScript array methods provide ready-to-use operations for working with arrays. The push() method adds an element at the end, pop() removes the last element, shift() removes the first element, and unshift() adds an element at the beginning.