Coming from C++ background when i first saw the array implementation in javascript i was like are you serious how can it be so straight forward? In C++ we had to first define the variable type, specify the name of the array followed by square brackets and specify the number of elements it should store but in javascript we had to just use const
or let
and specify the array name we can store any type of element in javascript array
// creating array in javascript
let arrayName = ["dog", "cat","lion","tiger",20]
and for printing an array
//printing an array
console.log(arrayName)
In javascript also the indexing of array starts with 0 only.
Below are some important array methods
1. Length
To know the length of array or number of elements in an array we use length
property.
let arrayName = ["dog", "cat","lion","tiger"]
console.log(arrayName.length)
//output
4
2. push()
The push()
method adds one or more elements to the end of an array.
let arrayName = ["dog", "cat","lion","tiger"]
arrayName.push("deer","rabbit")
console.log(arrayName)
//output
["dog", "cat","lion","tiger","deer","rabbit"]
3. pop()
The pop()
method is use to remove the last element of an array
let arrayName = ["dog", "cat","lion","tiger","deer","rabbit"]
console.log(arrayName.pop())
//output
rabbit
4. shift()
The shift()
method is use to remove the first element of an array
let arrayName = ["dog", "cat","lion","tiger","deer"]
console.log(arrayName.shift())
//output
dog
console.log(arrayName)
//output
["cat","lion","tiger","deer"]
5. unshift()
The unshift()
method adds one or more elements to the beginning of an array.
let arrayName = ["cat","lion","tiger","deer"]
arrayName.unshift("snail","monkey")
console.log(arrayName)
//output
["snail","monkey","cat","lion","tiger","deer"]
6. indexOf()
To know the index of an element in an array we use indexOf()
.
let arrayName = ["dog", "cat","lion","tiger","deer"]
console.log(arrayName.indexOf("cat"))
//output
1
7. slice()
slice()
method is used to access desired elements from an array. This method does not affect the main array rather gives a copy of desired elemnts.
let arrayName = ["dog", "cat","lion","tiger","deer"]
console.log(arrayName.slice(1,4))
//output
[ 'cat', 'lion', 'tiger' ]
console.log(arrayName)
//output
[ 'dog', 'cat', 'lion', 'tiger', 'deer' ]
8. splice()
splice()
method is use to remove specific elements from an array and it also modifies the array. You can also insert additional elements in place of removed elements.
syntax: splice(start, deleteCount, item)
let arrayName = ["dog", "cat","lion","tiger","deer"]
console.log(arrayName.splice(1,3,9))
//output
[ 'cat', 'lion', 'tiger' ]
console.log(arrayName)
//output
[ 'dog', 9, 'deer' ]