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:
var fruits = ["Apple","Orange","Grapes","Mango","Pineapple"];: Creates an array namedfruitswith initial values.document.write(fruits[0]);: Accesses and prints the element at index0(first element) of thefruitsarray ("Apple").document.write(fruits[2]);: Accesses and prints the element at index2of thefruitsarray ("Grapes").fruits.push("Kiwi");: Adds"Kiwi"to the end of thefruitsarray.fruits[3] = "Cherry";: Modifies the element at index3of thefruitsarray to"Cherry".fruits.pop();: Deletes the element at last index .fruits.splice(2, 1);: Deletes one element at index2from thefruitsarray (removes"Grapes").var x = fruits.length;: Retrieves the length of thefruitsarray.document.write(<ul>"; ...: Constructs an HTML list (<ul>...</ul>) dynamically using aforloop to iterate overfruitsarray elements and prints them in list items (<li>...</li>).