JavaScript Array Reference

Array Object The Array object is used to store multiple values in a single variable: var cars = [“Saab”, “Volvo”, “BMW”]; Array indexes are zero-based: The first element in the array is 0, the second is 1, and so on. For a tutorial about Arrays, read our JavaScript Array Tutorial. Array Properties Property Description constructor Returns the function that […]

JavaScript Array Iteration Methods

Array iteration methods operate on every array item. Array.forEach() The forEach() method Calls a function once for each array element. Example var txt = “”; var numbers = [4, 9, 16, 25]; numbers.forEach(myFunction); function myFunction(value, index, array) { txt = txt + item + “<br>”; } Try it Yourself » Note that the function takes 3 arguments: The item value The item index […]

JavaScript Sorting Arrays

The sort() method sorts an array alphabetically: Example var fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; fruits.sort();        // Sorts the elements of fruits Try it Yourself » Reversing an Array The reverse() method reverses the elements in an array. You can use it to sort an array in descending order: Example var fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; fruits.sort();        // First sort the elements of fruits fruits.reverse();     // Then reverse the […]

JavaScript Array Methods

Converting Arrays to Strings The JavaScript method toString() converts an array to a string of (comma separated) array values. Example var fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; document.getElementById(“demo”).innerHTML = fruits.toString(); Result Banana,Orange,Apple,Mango Try it Yourself » The join() method also joins all array elements into a string. It behaves just like toString(), but in addition you can specify the separator: Example var fruits = [“Banana”, “Orange”, “Apple”, “Mango”]; […]

JavaScript Arrays

JavaScript arrays are used to store multiple values in a single variable. Example var cars = [“Saab”, “Volvo”, “BMW”]; Try it Yourself » What is an Array? An array is a special variable, which can hold more than one value at a time. If you have a list of items (a list of car names, for example), storing […]