JavaScript Array and it’s methods
JavaScript Arrays
An array in JavaScript is a data structure that can store multiple values of the same type. Arrays are zero-indexed, which means that the first element in an array has an index of 0, the second element has an index of 1, and so on.
Many different methods can be used to work with JavaScript arrays. Some of the most common methods include:
push(): This method adds an element to the end of an array.
pop(): This method removes the last element from an array.
shift(): This method removes the first element from an array.
unshift(): This method adds an element to the beginning of an array.
slice(): This method creates a new array that contains a slice of the original array.
indexOf(): This method returns the index of the first occurrence of a value in an array.
lastIndexOf(): This method returns the index of the last occurrence of a value in an array.
sort(): This method sorts the elements of an array.
reverse(): This method reverses the order of the elements in an array.
These are just a few of the many methods that can be used to work with JavaScript arrays. For more information, please refer to the MDN Web Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array.
Here are some examples of how to use JavaScript array methods:
JavaScript
const fruits = ["apple", "banana", "orange"];
// Add an element to the end of the array.
fruits.push("grape");
// Remove the last element from the array.
fruits.pop();
// Remove the first element from the array.
fruits.shift();
// Add an element to the beginning of the array.
fruits.unshift("kiwi");
// Create a new array that contains a slice of the original array.
const firstTwoFruits = fruits.slice(0, 2);
// Return the index of the first occurrence of "banana" in the array.
const bananaIndex = fruits.indexOf("banana");
// Return the index of the last occurrence of "banana" in the array.
const lastBananaIndex = fruits.lastIndexOf("banana");
// Sort the elements of the array in alphabetical order.
fruits.sort();
// Reverse the order of the elements in the array.
fruits.reverse();
Use code with caution. Learn more
content_copy
Conclusion
JavaScript arrays are a powerful tool that can be used to store and manipulate data. The methods that are available for working with arrays make them a versatile and flexible data structure. By understanding how to use these methods, you can write JavaScript code that is more efficient and easier to read.