Saif Ur Rehman
JavaScript
JavaScript arrays are one of the most powerful and versatile data structures in web development. They allow us to store and manipulate collections of data in a variety of ways. This blog post will teach you the most important JavaScript array methods, including push(), pop(), unshift(), shift(), unshift(), indexOf(), splice(), slice(), join(), and reduce(). By learning these methods, you can write more efficient and powerful code.
1. push() By utilizing the push() method, you can effortlessly append an element to the end of an array, like in the instance below where "banana" is added to the fruits array's end:
push()
fruits = ['apple', 'orange', 'pear']; fruits.push('banana'); console.log(fruits); // Output ['apple', 'orange', 'pear', 'banana']
2. pop() By utilizing the pop() method, the last item within an array can be extracted and deleted, with its value being returned. For instance, take the following code where the last element of the fruits array is removed and stored within the lastFruit variable:
pop()
fruits
lastFruit
fruits = ['apple', 'orange', 'pear']; lastFruit = fruits.pop(); console.log(lastFruit); // Output: pear console.log(fruits); // Output: ['apple', 'orange']
3. unshift() The unshift() method adds an element to the beginning of an array. For example, the following code would add the element "banana" to the beginning of the array fruits:
unshift()
fruits = ['apple', 'orange', 'pear']; fruits.unshift('banana'); console.log(fruits); // Output ['banaba', 'apple', 'orange', 'pear']
4. shift() The shift() method removes the first element from an array and returns it. For example, the following code would remove the first element from the array fruits and store it in the variable firstFruit:
shift()
firstFruit
fruits = ['apple', 'orange', 'pear']; firstFruit = fruits.shift(); console.log(firstFruit); // Output: apple console.log(fruits); // Output: ['orange', 'pear']
5. indexOf() The indexOf() method returns the first index at which a given element can be found in an array, or -1 if it is not present.
indexOf()
const fruits = ['apple', 'banana', 'orange']; const orangeIndex = fruits.indexOf('orange'); console.log(orangeIndex); // Output: 2
How To Play m3u8 File in HTML Video Player Using JavaScript
This project is protected to maintain the privacy of our valued clients.
Remember, the password is valid for one-time use and will grant access to all secured projects. Need assistance? Please feel free to contact us! Best regards.
Hi There! How can I help you?
Chat with us 👋