JavaScript Array

 

JavaScript Array

Sometimes in application you may dealing with list of objects.

For example: The list of products in a shopping cart or the list of colours. The user will select. In that situation we use an array to store the list.

let selectedColors = []    called as array  literal, Empty array

let selectedColors = [‘red’, ‘blue’];

console.log (selectedColors);

or


console.log (selectedColors[0]);  

specify the index

Now check in console


Answer: (2) [Red, blue]

0: “red” index of first element is 0


1:” blue” index of second element is 1

0 and 1 are index determine the Position

We can add another element to the array in dynamic, so array will Expand.

selectedColors [2]= ‘green’;       3rd item in the Array

Now in console we have three elements, the length Is dynamic, it can change and also the type of objects in the array is also dynamic, in other programming language where every item or every object in the array should have same type. But in JavaScript we can store different types in array. So, we can also make last element in number.

For Example:

selectedColors [3] = 1;

Now we have 3 strings and 1 number.

So, the object in the array as well as the size of the array are dynamic.

So technically an array is an object, it has punch of key value called property we can access the property by using the dot notation

For Example:

Now in console type.

Typeof selectedColors

Answer = “object”

So, array is an object in JavaScript.

Now

let selectedColors = [‘red’,’blue’];

selectedColors [2] = green;

selectedColors [3] = 1;


console.log (selectedColors.length);  

Using dot notation. We can use property of the object.

There are lot of properties for array one of the properties is length. This property returns number of items or elements in array.

Save the changes and check in console

Answer  4

Now we have four elements in this array.

Post a Comment

Share your thoughts here

Previous Post Next Post