JavaScript Arrays – Beginner Book
Arrays in JavaScript
Array is a collection of items. Arrays are represented by square brackets [] and each
element in the array has an index.
Index always starts from 0.
Example:
let a = ["raj", 1, true];
let arr = [5,4,8,9,0,-3];
Accessing Elements:
arr[1] // 4
[Link] // 6
arr[23] // undefined
--------------------------------------------------
Array Methods
1. push()
Adds elements at the end of the array.
[Link](value1, value2)
2. pop()
Removes the last element of the array.
[Link]()
3. unshift()
Adds elements at the beginning.
[Link](value1, value2)
4. shift()
Removes the first element.
[Link]()
5. splice(start, deleteCount, items)
Used to add or remove elements at any index.
Example:
let names = ["raj","shyam","shekhar","john","sita"];
[Link](1,2);
--------------------------------------------------
Practice Task
let friends = ["sheldon","monica","joey","rachel","ross","penny"];
1. Remove sheldon and add chandler
[Link](0,1,"chandler")
2. Remove penny and add pheobe
[Link](5,1,"pheobe")
3. Insert emma between rachel and ross
[Link](4,0,"emma")
--------------------------------------------------
Searching & Utility Methods
indexOf()
Returns first occurrence index.
reverse()
Reverses array.
join()
Converts array to string.
--------------------------------------------------
Higher Order Functions
forEach()
Used to iterate but does NOT return a new array.
map()
Returns a new array.
filter()
Returns only elements that satisfy condition.
find()
Returns first matching element.
some()
Returns true if at least one condition is satisfied.
every()
Returns true only if all conditions are satisfied.