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;
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];
ARRAY SYNTAX
const arrayname [item1,itme2,.....];
Using JavaScript Keyword new
const arrayname = new (item1,item2,....);
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));
example program
const num = [10,20,30,40];
console.log(num[2]);
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]);
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]);
}
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
Top comments (1)
I found the section on accessing array elements particularly helpful, especially the example that demonstrates how to retrieve the last element of an array using
arrayname[arrayname.length-1]. This is a common use case, and it's good to see it explicitly covered. The use of aforloop to iterate over the array elements is also a great illustration of how to work with arrays in a more dynamic way. One thing that might be worth exploring further is how to handle cases where the array index is out of bounds, perhaps by using optional chaining or try-catch blocks to prevent errors. How do you typically handle such edge cases in your own JavaScript projects?