What are arrays?
Arrays are the collection of elements that can hold various datatypes like numbers, string, objects. They provide a powerful way to manage and organize multiple values under a single variable name. Arrays are initialized in square brackets and the indexing starts from 0.
Array are object and user-defined datatypes. It is mutable that means it can be modified when necessary.
Creating Array
Using Array Literals
const array = [ "apple" , 25 , true , "grapes" , { id : 1, task: "fruits" } ] // this is how you can store any element in an array
Using Array Constructor
const construct = new Array ("Apple", 25 , "black" , true)
Accessing Array elements
Array elements can be accessed using the array name followed by the square brackets followed by the index. With this we can get any element from the array.
Indexing starts from 0
console.log( array[2] ) // true.
array[2] = false
console.log( array[2] ) // false
Properties
Length
// Length
const array = [1,2,4,5,9]
console.log( array.length ) // 5
array.length = 10 //length of array is now 10
console.log(array)
/* increasing the length of array leads an array to add empty slots */
array.length = 2 // length of array is now 2
console.log(array)
/* decreasing the length of array leads to delete the array elements */
Methods
push()
const abc = [1,2,3,4,5]
abc.push(6)
console.log(abc) // [1,2,3,4,5,6]
pop()
abc.pop()
console.log(abc) // [1,2,3,4,5]
shift()
console.log(abc.shift()) // 1
console.log(abc) // [2,3,4,5]
unshift()
abc.unshift(10,8)
console.log(abc) // [10,8,2,3,4,5]
slice()
console.log(abc.slice(1,3)) // [8,2]
splice()
// syntax
// array.splice(start,number of deletion, to be added,to be added ...)
const a = [1,2,3,4,5]
console.log(a.splice(1,2,8,6)) // [2,3]
console.log(a) // [1,8,6,4,5]
concat()
const a = [2,3,4]
const b = [7,8,9]
const c= a.concat(b)
console.log(c) // [2, 3, 4, 7, 8, 9]
join()
const a = [1,2,3]
const b = a.join(' + ')
console.log(b) // 1 + 2 + 3
indexOf()
const a = [ "apple" ,"banana", "cherry"]
console.log(a.indexOf("cherry")) // 2
sort()
const a = [5,8,9,2,1,0]
console.log(a.sort()) // [0, 1, 2, 5, 8, 9]
reverse()
// let's take above array
console.log(a.reverse()) // [9, 8, 5, 2, 1, 0]
delete()
// let's take above array again
delete a[5]
console.log(a) // [9, 8, 5, 2, 1, empty]
toString()
const ab = [1,2,4,5,6]
const str = ab.toString()
console.log(str) // 1,2,4,5,6
console.log(typeof (ab)) // object
console.log(typeof (str)) // string
Congratulations !!!!! you have mastered JavaScript Array.
If you think I have missed some methods then feel free to share your views on any platform available in my profile. Here I mention some
Instagram ----> React Mastery Series is going on
I hope you have learned something new today. If yes, then follow me for more such valuable content.
Written By MOHIT SONI