Arrays

An array is a special variable, which can hold more than one value

  • array are special type of object
  • typeof array "object"
  • it contain ordered list of values
  • keys are indexed (starts from 0..)
  • Use square bracket [] because key is number

Creating an array

For creating an array we use square bracket "[]"

Types of array

  • Empty array
    let arr = []
    
  • array of number
    let number = [1,2,3,4]
    
  • array of strings
    let vehicles = ['bike','car','bus']
    
  • Mixed array
    let mix = [143,'hello',true,undefined]
    
    D/w array and object
  • object contain a key and value pair, where we define the key but in
  • arrays we dont have to define the key it is defined by javascript

Operation perform on arrays

  • Accessing
  • Adding
  • Updating
  • deleting

Accessing

To aceesing the element of an array, we use square bracket

ex-

let vehicles = ['bike','car','bus']
vehicles[0]
'bike'

vehicles[1]
'car'

Adding

To add new element to array we use push() method. ex-

let vehicles = ['bike','car','bus']
vehicles.push('truck)  '
'truck'

vehicles
['bike','car','bus','truck']

Updating

To update array we use name of the array with square bracket '[]' inside bracket give the index of element want to update

let fruits = ['apple','mango','papaya']
fruit[2]='banana'
'banana'

fruits
['apple','banana','papaya']

Deleting

delete keyword and name of the array with square bracket inside bracket give the index want to delete

let fruits = ['apple','banana','papaya']
delete fruits[0]
true

fruits
[empty, 'banana', 'papaya']

Note

Every array has speacial property called length ,which give you number of element in that array.

ex-

let vehicles = ['bike','car','bus']
vehicles.length
3

Iterating Over Arrays

There are two different ways to iterate over arrays.

  1. for loop (more chance of error)
  2. for..of loop (less chance of error)

    for.. of loop is new edition to the javascript family that makes accessing element of the array really really easy.

ex- for..of loop

let colors = ['red','white','green']
for(let color of colors){
console.log(color);
}

Output-

red
white
green

ex- for loop

let colors = ['red','white','green']
for(let i=0; i<colors.length ; i++){
console.log(colors[i]);
}

Output-

red
white
green