Javascript Arrays

JavaScript Arrays:-

What is an Array:-

Arrays are complex variables that allow us to store more than one value or a group of values under a single variable name. JavaScript arrays can store any valid value, including strings, numbers, objects, functions, and even other arrays, thus making it possible to create more complex data structures such as an array of objects or an array of arrays.

Let’s suppose you want to store the name of colors in your JavaScript code. Storing the color names one by one in a variable could look something like this:

Example

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8″>
<title>JavaScript Storing Single Values</title>
</head>
<body>
<script>
// Creating variables
var color1 = “Red”;
var color2 = “Green”;
var color3 = “Blue”;

// Printing variable values
document.write(color1 + “<br>”);
document.write(color2 + “<br>”);
document.write(color3);
</script>
</body>
</html>

Output:-

Red
Green
Blue

Creating an Array:-

The simplest way to create an array in JavaScript is enclosing a comma-separated list of values in square brackets ([]), as shown in the following syntax:

var myArray = [element0, element1, …, elementN];

Array can also be created using the Array() constructor as shown in the following syntax. However, for the sake of simplicity previous syntax is recommended.

var myArray = new Array(element0, element1, …, elementN);

Here are some examples of arrays created using array literal syntax:

<!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>

Output:-

Red,Green,Blue
Apple,Banana,Mango,Orange,Papaya
London,Paris,New York
John,Wick,32