array in javascript

An array is like a list that can hold multiple pieces of information at once. 

It's a way to organize data in a structured manner.


Syntax: To create an array, you use square brackets [] and separate each item with a comma.


var   array_name=[ val_1,  val_2 ,   val_3  ,  val_4 ,  val_n ];

Example:

let fruits = [ "apple" ,  "banana"  ,  "orange" ] ; 

var ages=[ 45, 2 , 2 , 45 , 3  ];

const details=[ "som"  , true  , 4.5 ,  4 ];

    


arrays are Indexed: Each item in an array has a numbered position, starting from 0. 

This position is called the index.

To access an item in an array, you use square brackets [] with the index number.


    Example:


<script>

    let fruits = [ "apple" ,  "banana"  ,  "orange" ] ; 

    document.write(fruits[0]); // Output: "apple"

    document.write(fruits[1]); // Output: "banana"

</script>    


Length: Arrays keep track of how many items they contain using the length property.

To find the length of an array, you use the length property.

example:

<script>

var ages=[ 45, 2 , 2 , 45 , 3  ];

   document.write(ages.length); 

</script>  

  

Output: 5


Iterating Over Arrays: You can loop through all the items in an array to perform actions on each one.

Example:

<script>


    let fruits = [ "apple" ,  "banana"  ,  "orange" ] ; 

    for (let i = 0; i < fruits.length; i++) 

    {

        document.write(fruits[i]);

    }

</script>

That's a basic overview of arrays in JavaScript! They're incredibly versatile and useful for storing and manipulating collections of data.

0 Comments