ARRAYS IN JS PART - 1

javascript dev.to

ARRAY

Array is one of the object in the JavaScript. In array we can store multiple values in different datatype.

Why uses Array ?

If there is a list of items we can store in a single variable .

without an array

let num1=10;
let num2=20;
let num3=30;
let num4=40;
Enter fullscreen mode Exit fullscreen mode

In this code we declare the num1,num2,num3 and num4 variable to initialize the four number. If we use the array means we can store all the number in a single variable.

const num = [10,20,30,40];
Enter fullscreen mode Exit fullscreen mode

ARRAY SYNTAX

const arrayname [item1,itme2,.....];
Enter fullscreen mode Exit fullscreen mode

Using JavaScript Keyword new

const arrayname = new (item1,item2,....);
Enter fullscreen mode Exit fullscreen mode

How to accessing the array elements

Array can be access by the referring index number. If we want to access the single the element in array means,

console.log(arrayname(referring index number));
Enter fullscreen mode Exit fullscreen mode

example program

const num = [10,20,30,40];
console.log(num[2]);
Enter fullscreen mode Exit fullscreen mode

output:
30

In the above code num variable store the 4 number. In array the index value will be starting in 0 .So num = [10,20,30,40],
index value of 10 is 0
index value of 20 is 1
index value of 30 is 2
index value of 40 is 3
so what the output value is 30.

const num = [10,20,30,40];
console.log(num[num.length-1]);
Enter fullscreen mode Exit fullscreen mode

output:
40

In these code we access the last element of the array. By using the formula (arrayname[arrayname.length-1]).
In the above code num = [10,20,30,40] the index start from 0,1,2,3 actually there are 4 num and length is also 4 so length-1 means we can access the last element in the array .

const num = [10,20,30,40];
for (let i =0;i<5;i++){
console.log(num[i]);
}
Enter fullscreen mode Exit fullscreen mode

output:
10
20
30
40

In the above code we are access the all the element in the array by using the for loop.

To be Discussed

Array convert into String
Display the array using json
Array element can be a object

Source: dev.to

arrow_back Back to Tutorials