/  Technology   /  JavaScript Arrays 
js2

JavaScript Arrays 

 

What is an array?

An array is a collection of similar type of data and is used to store different elements in a single variable.

For example, if we want to store the names of 45 people then we can create an array to store 45 names.

How to declare array?

There are 2 ways to declare the array

  1. Initialize it by using square bracket
  2. New Array keyword followed by parenthesis.
  • Example for initializing array by using square bracket
var array= ['null',"array",`object`]
  • Example for initializing array by using New Array keyword.
var array= new Array ('null',"array",`object`)
console.log(typeof(array)); // object

How to access individual elements in an Array?

Array can be accessed by using index value.

var array= ['null',"array",`object`]

array[0] =null           First Element

array[1] = array       Second Element

array[2] = object      Third Element

 

Index value starts from 0

Index value = (no of elements in a array) - 1

 

Leave a comment

Javascript-Arrays

 

An array is a single variable that is used to store various elements(hold more than one value at a time.). You want to store a list of elements and access them by a single variable.

 

Creating an Array:

 

Syntax:

 

var array_name = [item1, item2, ...];

 

Example:

 

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

<p id="demo"></p>

<script>
var cars = ["html", "css", "javascript"];
document.getElementById("demo").innerHTML = cars;
</script>

</body>
</html>

 

OUTPUT:

 

JavaScript Arrays

html,css,javascript

 

3 ways to construct array in JavaScript:

 

  1. By array literal
  2. By creating instance of Array directly (using new keyword)
  3. By using an Array constructor (using new keyword)

 

JavaScript array literal:

 

syntax :

 

var arrayname=[value1,value2.....valueN];

 

values are contained inside [ ] and separated by , (comma).

 

Example:

 

<html>
<body>
<script> 
var emp=["Html","CSS","JAVASCRIPT"]; 
for (i=0;i<emp.length;i++){ 
document.write(emp[i] + "<br/>"); 
} 
</script> 
</body>
</html>

 

OUTPUT:

 

Html

CSS

JAVASCRIPT

 

JavaScript Array directly (new keyword):

 

syntax :

 

var arrayname=new Array();

 

new keyword is used to create instance of array.

 

Example:

 

<html>
<body>
<script> 
var i; 
var emp = new Array(); 
emp[0] = "HTML"; 
emp[1] = "CSS"; 
emp[2] = "JAVASCRIPT"; 

for (i=0;i<emp.length;i++){ 
document.write(emp[i] + "<br>"); 
} 
</script> 
</body>
</html>

 

OUTPUT:

 

HTML

CSS

JAVASCRIPT

 

JavaScript array constructor (new keyword):

 

Create an instance of an array by passing arguments in the constructor so that we don’t have to provide value explicitly.

 

Example:

 

<html>
<body>
<script> 
var emp=new Array("hello","welcome","I2tutorials"); 
for (i=0;i<emp.length;i++){ 
document.write(emp[i] + "<br>"); 
} 
</script> 
</body>
</html>

 

OUTPUT:

 

hello

welcome

I2tutorials