The topic contains a brief explanation of JavaScript Array and how to create and manipulate JavaScript arrays.
Here we discuss 7 most used JavaScript array functions and it’s working with example,
- length()
- push()
- pop()
- shift()
- unshift()
- indexOf()
- foreach()
What is an Array
Create a JavaScript Array
1 2 3 4 |
var myArray = [1, 2, 3, 4]; var langNamesArray = ["Java", "PHP", "Wordpress"]; //Arrays in JavaScript can hold multiple types of data, as shown. |
Access an Array Item
On the time accessing an array from a variable we use an array index number. On JavaScript array operation, if you want the last element of an array, use ArrayName.length function and subtract 1 for the last array element.
1 2 3 4 5 6 7 |
var first = langNamesArray[0]; // Java var last = langNamesArray[langNamesArray.length - 1]; // Wordpress |
Add an element at the End of an Array
1 2 3 4 |
var newLength = langNamesArray.push('Laravel'); // ["Java", "PHP", "Wordpress", "Laravel"] |
Remove last element in Array
For removing operation in an array element, we use an array pop function. Array pop function removes an array element from last of an array.
1 2 3 4 5 |
var last = langNamesArray.pop(); // remove Laravel (from the end) // ["Java", "PHP", "Wordpress"]; |
Remove from the front of an Array
Using array shift function to remove first element of an array.
1 2 3 4 5 |
var first = langNamesArray.shift(); // remove Java from the front // ["PHP", "Wordpress"]; |
Adding the first element to an Array
For adding the first index element in an array we use array unshift function. Check below array unshift function uses the example :
1 2 3 4 5 |
var newLength = langNamesArray.unshift('Laravel') // add to the front // ["Laravel", "PHP", "Wordpress"]; |
Find the index of an Array Element
For finding the index of an array element we use array indexOf function with array element or value of array parameter. Check the below example for explanation.
1 2 3 4 5 6 7 |
langNamesArray.push('Laravel'); //["Laravel", "PHP", "Wordpress"] var pos = langNamesArray.indexOf('PHP'); // 1 |
Loop in an Array
For getting all elements at once we use a loop in an array. In JavaScript array, we use the forEach loop. In the below example, we print an array element name and its index.
1 2 3 4 5 6 7 8 |
langNamesArray.forEach(function(item, index, array) { console.log(item, index); }); // Java 0 // PHP 1 // Wordpress 2 |
Also Check:
- DOM | DOCUMENT OBJECT MODEL
- SELECTION IN CSS | CSS ::SELECTION
- 3D LOADER USING CSS
- PERCENTAGE DIFFERENCE CALCULATOR USING JQUERY & PHP
Know more about JavaScript Array Functions,
https://www.php.net/manual/en/function.array.php
Happy Coding..!
8 Replies to “7 Most Useful JavaScript Array Functions”