Comprehensive Guide to Arrays in JavaScript: Creation, Methods, and Concepts
1.
Prepared By: KaleJ. N.
Arrays in Java Script
1. What is an Array?
An array is a special variable that can hold multiple values.
Example:
let numbers = [10, 20, 30, 40];
2. Creating Arrays
Method 1: Array Literal
let fruits = ["Apple", "Banana", "Mango"];
Method 2: Using new Array()
let nums = new Array(1, 2, 3, 4);
3. Accessing Elements
let arr = ["A", "B", "C"];
arr[0];
arr[arr.length - 1];
4. Array Property
length
let arr = [1,2,3];
arr.length; // 3
5. Modifying Arrays
push() - Add at end
unshift() - Add at beginning
pop() - Remove from end
shift() - Remove from beginning
6. Looping Through Arrays
For Loop
for(let i = 0; i < arr.length; i++){
console.log(arr[i]);
}
for...of
for(let value of arr){
console.log(value);
}
2.
Prepared By: KaleJ. N.
forEach()
arr.forEach(function(item){
console.log(item);
});
7. Important Array Methods
map() - Creates new array
It is an array method that:
Iterates over each element
Applies a function to each element
Returns a new array
Does NOT modify the original array
filter() - Filters elements
filter() is an array method that:
Iterates over each element
Checks a condition
Returns a new array with only elements that satisfy the condition
Does NOT modify the original array
reduce() - Reduces to single value
reduce() is an array method that:
Iterates over each element
Combines all elements into one single value
Returns a single output (number, object, array, string, etc.)
Does NOT modify the original array
It is used for sum, product, grouping, counting, flattening, etc.
sort() - Sorts array
reverse() - Reverses array
3.
Prepared By: KaleJ. N.
8. Spread Operator
The spread operator […] is used to expand elements of an array into individual values. It
helps in copying arrays, merging arrays, and adding new elements without modifying the
original array.
Example:
let arr2 = [...arr1, 4, 5]; → Creates a new array by copying arr1 elements and adding 4 and 5.
9. Destructuring
Destructuring is a feature in JavaScript that allows you to extract values from arrays or
objects and assign them to variables in a simple way.
let [a, b] = [10, 20];
10. Important Concepts
- Arrays are objects
- Dynamic size
- Can store mixed data types
11. Shallow vs Deep Copy
Shallow Copy:
let arr2 = arr1;
This does not create a new array.
It only copies the reference (memory address).
Both arr1 and arr2 point to the same array.
Proper Copy:
let arr2 = [...arr1];
This creates a new array and copies elements.