In this article, we will be discussing arrays in javascript and their methods.
In simple words, an array is a collection of different items or different datatype stored under a common name Array in javascript is literally an easy way to create an array array with the different items :
let arr = ["java","HTML","python","javascript","CSS"]
Array with different datatype
let arr2 = ["hello",23,45.6,true,'h']
Javascript Array methods:
- length
We use length to find length of the array
OUTPUT: 5console.log(arr2.length)
- Indexing If we wanted to access the array we can access it through the name like arr2 but, if we wanted to access the individual element from it for that we use indexing NOTE : Indexing starts from 0 arr2[3] OUTPUT: true
- Slice:
Slice is a method that returns a selected element through a new array
OUTPUT: [23,45.6]arr2.slice(1,3)
splice Splice is a method wich adds new value in a given specific index or replaces the value with the existing element arr2.splice(index,1|2,"some value") 1- adding element 2- replacing the with existing element
arr2.splice(3,1,"welcome")
OUTPUT: ["hello", 23, 45.6, "welcome", "h"]
pop Pop is a method that is used to remove the last element from the existing array
arr2.pop()
OUTPUT: ["hello", 23, 45.6, "welcome"]
- Shift: The shift is used to remove the element at the front from the exiting element This is just like the pop but the pop will removes last element from it , but shift will remove the front element from the array
arr2.shift()
OUTPUT: [23, 45.6, "welcome"]
- unshift
OUTPUT: ["python","javascript", 23, 45.6, "welcome"]arr2.unshift("python","javascript")
concat Concat is a method that is used to concatenate two array
let array1 = ["python","javascript","HTML","CSS"] let array2 = [12,33,56,34,67] console.log(array1.concat(array2)
OUTPUT: ["python","javascript","HTML","CSS",12,33,56,34,67]
includes It is a method that checks the index and the element we provided and returns a boolean value
array2.includes(value,index)
array1.includes(12,"HTML")
OUTPUT: true
9.indexof This is an method which provide index of the element
console.log(arr1.indexOf("HTML"));
OUTPUT: 2
- toString
This is an method that convert array into string
OUTPUT: "python","javascript","HTML","CSS",12,33,56,34,67console.log(array1.toString());
THANK YOU EVERY ONE HAVE A NICE DAY