SimpleTuts.com

JavaScript Arrays

In JavaScript, arrays are used to store multiple values in a single variable. They are dynamic, meaning you can add or remove elements, and they can hold elements of different types.

let fruits = ["Apple", "Banana", "Cherry"];

Here's an example of using arrays in JavaScript:

HTML file


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Arrays in JavaScript</title>
</head>
<body>
    <script src="arrays.js"></script>
</body>
</html> 

JavaScript File (arrays.js)


//Array Declaration
var fruits = ["Apple","Orange","Grapes","Mango","Pineapple"];

//Print all array values
document.write(fruits);

//Print a single value from array
document.write("<br>"+fruits[0]);
document.write("<br>"+fruits[2]);


//Add a new value to array
fruits.push("Kiwi");
document.write("<br>"+fruits);


//Change an array value
fruits[3]="Cherry";
document.write("<br>"+fruits);

//Removes the last element
fruits.pop(); 
document.write("<br>"+fruits);

//Delete an element in a specific index
fruits.splice(2,1)
document.write("<br>"+fruits);


//Find the length of an array
var x = fruits.length;
document.write("<br>Length = "+x);
 

//Print array elements in HTML element
document.write("<ul>");
for(var i=0;i<x;i++){
    document.write("<li>"+fruits[i]+"</li>");
}
document.write("</ul>");
Run Code

Explanation of the example: