What is array in javascript?

The simplest way to create an array in JavaScript is enclosing a comma-separated list of values in square brackets ([])

File name : index.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Creating Arrays in JavaScript</title>
</head>
<body>
<script>
// Creating variables
var colors = ["Red", "Green", "Blue"];
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
var cities = ["London", "Paris", "New York"];
var person = ["John", "Wick", 32];

// Printing variable values
document.write(colors + "<br>");
document.write(fruits + "<br>");
document.write(cities + "<br>");
document.write(person);
</script>
</body>
</html>

Accessing the Elements of an Array

File name : index.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Access Individual Elements of an Array</title>
</head>
<body>
<script>
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

document.write(fruits[0] + "<br>"); // Prints: Apple
document.write(fruits[1] + "<br>"); // Prints: Banana
document.write(fruits[2] + "<br>"); // Prints: Mango
document.write(fruits[fruits.length - 1]); // Prints: Papaya
</script>
</body>
</html>

Getting the Length of an Array

File name : index.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Get the Length of an Array</title>
</head>
<body>
<script>
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
document.write(fruits.length); // 0utputs: 5
</script>
</body>
</html>

Looping Through Array Elements

File name : index.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Loop Through an Array Using For Loop</title>
</head>
<body>
<script>
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

// Iterates over array elements
for(var i = 0; i < fruits.length; i++){
document.write(fruits[i] + "<br>"); // Print array element
}
</script>
</body>
</html>





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here