Define an array in javascript

We need not declare arrays before we use them, as like other javascript variables, however declaring is a good habit and best programming practice.
Here we will learn to create single dimensional javascript arrays.

You can declare an Array in Javascript in three different ways.

a) Array Literal

We can declare an array in javascript using Array LiteralĀ  as below:

var fruitsArr = ["Apple", "Mango", "Banana", "Chickoo", "Tomato"];

OR

var fruitsArr;
fruitsArr[0] = "Apple";
fruitsArr[1] = "Mango";
fruitsArr[2] = "Banana";
fruitsArr[3] = "Chickoo";
fruitsArr[4] = "Tomato";

OR

var fruitsArr = [];
var fruitsArr = ["Apple", "Mango", "Banana", "Chickoo", "Tomato"];

b) Array Constructor

Another way of declaring an array is using the “new” keyword to create instance of Array in memory

var fruitsArr = new Array("Apple", "Mango", "Banana", "Chickoo", "Tomato");
OR 

var fruitsArr = new Array();
fruitsArr[0] = "Apple";
fruitsArr[1] = "Mango";
fruitsArr[2] = "Banana";
fruitsArr[3] = "Chickoo";
fruitsArr[4] = "Tomato";

c) Implicit Declaration

In this way of declaring, we call function whose return types are array. This is an indirect way of creating an array. We will using string split() method here for our demonstration.


var fruitsStr = "Apple-Mango-Banana-Chickoo-Tomato"; var fruitsArr = fruitsStr.split("-");

Output of this will be an array.

 

Click on below topics for step by step understanding.

How to get random element from Javascript Array and Display it.
Math.random() function in javascript
array.length in javascript
Math.floor() function in javascript

 

 

Comments are closed.