Loading, please wait...

Arrays

JavaScript Arrays

In JavaScript, Array defined as an object which stores multiple values of the same data type in a single variable.

The array is a special variable which helps to hold multiple values at a time. In case of arrays, we access the elements of an array by referring to their index number.

 

Mainly, data in arrays are surrounded by square brackets and separated by a comma (,). Data items in an array are only accessed by using their index numbers, and the index number of the first element in an array is always 0. The index number always starts with a number zero(0) and it goes on 1,2,…n.

While declaring an array if we do not pass any arguments then we add elements of an array dynamically.

 

So, Variables are used as:

var lang = “C”;
var lang1 = “C++”;
var lang2 = “Java”;

 

So, rather than create so many variables for a single data type, we use:

var lang = [“C”,”C++”,”Java”];

 

We can also create an array using the new keyword like:

var lang = new Array (“C”,”C++”,”Java”);

 

Syntax:

var arrayName = [value1,value2,….valueN];

 

Code:

<html>
<body>
<h2>JavaScript Arrays</h2>
<script>
var lang = ["C","C++","Java"];
document.write(lang);
</script>
</body>
</html>

In the above example, we define an array named as lang. Further, the elements in arrays are only accessed by their index numbers.

 

Output: