Site icon codippa

How to create array in javascript

What is an array

An array is a collection or a list of similar items logically grouped together. Similar items means values which represent a particular type of entity.
Examples are names of car companies, list of car models, laptop types, smartphone brands etc.
Similar items in above definition does NOT mean those which have the same data type such as a list of strings, list of numbers or a list of boolean values.
A single array in javascript can contain a string, an integer, a decimal value, an object and an array also. Thus, array in javascript is just a logical group of values.
Javascript array syntax
A javascript array is declared or initialized by surrounding it with square brackets (‘[‘ & ‘]’). Elements of the array are separated by a comma(,).
An array is assigned to a variable which becomes the name of the array.
Name of variable is user defined. It is not mandatory to assign an array to a variable but you have to do it if you want to use it anywhere else.
Thus, an array looks like

var cars = ['Honda', 'Hyundai', 'BMW', 'Audi'];

var laptops = ['Dell', 'Sony', 'Lenovo'];

// different data types
var hybrid = [1.2, 'string', true, 24];

// array inside array or nested array
var ramSizes = [8, 16, 32, 64];
var laptops = ['Dell', 'Sony', 'Lenovo', ramSizes];

You can also declare an empty javascript array and add elements to it later. Empty javascript array is defined by using empty square brackets and assigning to a variable.

Create javascript array
There are 2 ways to create an array

Add elements to array
Javascript arrays have a push method which allows you to add element to the array. It takes the element to add as argument and adds the element to the end of array.
push returns the length of the array. Also, more than 1 elements may be added to the array using push method. Example,

var evenNumbers = [0, 2, 4, 6];
evenNumbers.push(8);   // array becomes [0, 2, 4, 6, 8]
var length = evenNumbers.push(10, 12, 14);    // length will be 8

When an element is added to the array using push, it is appended at the end of the array.
Accessing array elements
Array elements are index based(index starts at 0) and its elements can be accessed using indexes. Syntax to access an array element is :

var element = arrayName[ elementIndex];

Thus, to access first element of an array, following syntax is used

var laptops = ['Dell', 'Sony', 'Lenovo'];
var l = laptops[1];     // This returns Sony

Loop array in javascript
A javascript array can be iterated using a for loop. Since array indexes start at 0, the loop starts from 0.
Also, array has a length property which returns the total number or count of elements in the array.
Thus, the last element of the array will have index = length – 1.
Therefore, to iterate over an array, a for loop starting from 0 to length – 1 can be used. Example,

var laptops = ['Dell', 'Sony', 'Lenovo'];
for (var index = 0; index < laptops.length; i++) {
   console.log('Laptop : '+laptops[index]);
}

In order to iterate over an array for...of loop can also be used. It is a newer feature in javascript. Syntax is:

let laptops = ['Dell', 'Sony', 'Lenovo'];
for (let laptop of laptops) {
   console.log('Laptop : '+laptop);
}

let followed by a name declares a variable. In each iteration, this variable contains the current array element.

Javascript array functions
Following are the commonly used javascript array methods

Method Description Usage
push Used to add an element to array.(Has been discussed above)
toString  Converts an array to a string of comma separated values var laptops = [‘Dell’, ‘Sony’, ‘Lenovo’];
laptops.toString();// returns Dell, Sony, Lenovo
pop Returns the last element of the array. The element is also removed from the array.  var laptops = [‘Dell’, ‘Sony’, ‘Lenovo’];
laptops.pop(); //returns Lenovo

/* array is now [‘Dell’, ‘Sony’] */
shift Returns the first element of the array. The element is removed from the array and all the remaining elements are shifted towards the left.  var laptops = [‘Dell’, ‘Sony’, ‘Lenovo’];
laptops.shift(); //returns Dell

/* array is now [‘Sony’, ‘Lenovo’] */
join Returns a string combined with a separator. The separator is passed as an argument to this method.  var laptops = [‘Dell’, ‘Sony’, ‘Lenovo’];
laptops.join(‘ & ‘);
//returns Dell & Sony & Lenovo
unshift This method is opposite of shift method. It adds an element to the beginning of the array and shifts other elements to the right. The element to be added is passed as an argument to this method. This method returns the new length of the array. var laptops = [‘Dell’, ‘Sony’, ‘Lenovo’];
laptops.unshift(‘Apple’); //returns 4

/* array is now [‘Apple’, ‘Dell’, ‘Sony’, ‘Lenovo’] */
slice Accepts two integers as arguments and returns the array of elements whose indexes lie in between the two arguments. Note that the indexes are zero-based and array elements till (second argument – 1) are considered. var laptops = [‘Apple’, ‘Dell’, ‘Sony’, ‘Lenovo’];
laptops = laptops.slice(1,2);
// returns [‘Dell’]
sort This method sorts an array in alphabetical order. If the array is of numbers, then it sorts the array from low to high values. var laptops = [‘Apple’, ‘Dell’, ‘Sony’, ‘Lenovo’];
laptops.sort();
// returns [‘Apple’, ‘Dell’, ‘Lenovo’, ‘Sony’];
reverse Reverses the elements of the array. That is, last element becomes the first, second last becomes the second element and so on. var laptops = [‘Apple’, ‘Dell’, ‘Sony’, ‘Lenovo’];
laptops.reverse();
// returns [‘Lenovo’, ‘Sony’, ‘Dell’, ‘Apple’]
indexOf This method accepts an array element as argument and returns the index of that element inside the array. It returns -1 if the element does not exist in the array. This method can be used to check if an array contains an element. var laptops = [‘Apple’, ‘Dell’, ‘Sony’, ‘Lenovo’];
laptops.indexOf(‘Dell’);
// returns 1

How to recognize array
Suppose you want to test whether a given variable represents an array or not. One will suggest to use typeof operator.
But the problem is that typeof used on array will return “object“. This is because an array is also an object. So, the question is how to tell whether a variable represent an array.
Following methods will be useful in this case.

Method 1 : Using instanceof operator
instanceof operator used on array variable will return true if the variable is an array, false otherwise. Example,

var laptops = [‘Apple’, ‘Dell’, ‘Sony’, ‘Lenovo’];
laptops instanceof Array             // will return true

Method 2 : Using isArray method
Array object defines a method isArray which takes an argument which will return true if the argument is an array, false otherwise. Example,

 

var laptops = ['Apple', 'Dell', 'Sony', 'Lenovo'];
Array.isArray(laptops);              // returns true
var value = 5;
Array.isArray(value);                 // returns false
Array.isArray(new Array());       // returns true
Array.isArray();                         // returns false

This method was introduced in ECMAScript 5 and will not work in older browsers.
Method 3 : Using constructor property
Array variable has a constructor property. This property returns the function name which created the array. Converting the value to a string using toString method returns a string representation of this function.
Now, whether the variable is an array can be tested by checking the presence of “Array” in this string. Example,

var laptops = ['Apple', 'Dell', 'Sony', 'Lenovo'];
var functionName = laptops.constructor;      // returns Array()
var functionStr = functionName.toString();   // returns function Array() { [native javascript code] }
var isarray = functionStr.indexOf("Array") > -1;   // returns true

So, In this article, we looked at javascript arrays in detail.
Hope it was useful.  

Exit mobile version