Creating Arrays
JavaScript provides two primary ways to create arrays:
Literal Notation
const emptyArr = []; // Create an empty array
const singleValueArr = [7]; // Create an array with one element
const multiValueArr = [7, 8, 9]; // Create an array with multiple elements
Constructor Notation
const emptyArr = new Array(); // Create an empty array
const lengthDefinedArr = new Array(7); // Create an array with length 7 (empty elements)
const multiValueArr = new Array(7, 8, 9); // Create an array with multiple elements
Array Method Overview
| Method | ECMAScript Version | Functionality | Mutates Original Array |
|---|---|---|---|
concat() |
ES5 and earlier | Merges arrays/values and returns the combined result | ❌ No |
join() |
ES5 and earlier | Converts array elements to a string separated by a specified delimiter | ❌ No |
pop() |
ES5 and earlier | Removes and returns the last element of the array | ✅ Yes |
shift() |
ES5 and earlier | Removes and returns the first element of the array | ✅ Yes |
unshift() |
ES5 and earlier | Adds elements to the start, returns new array length | ✅ Yes |
push() |
ES5 and earlier | Adds elements to the end, returns new array length | ✅ Yes |
reverse() |
ES5 and earlier | Reverses element order, returns the reversed array | ✅ Yes |
slice() |
ES5 and earlier | Extracts a subset of elements, returns new array | ❌ No |
sort() |
ES5 and earlier | Sorts elements (default lex order), returns sorted array | ✅ Yes |
splice() |
ES5 and earlier | Removes/replaces/adds elements, returns removed elements | ✅ Yes |
toString() |
ES5 and earlier | Converts array to comma-separated string | ❌ No |
valueOf() |
ES5 and earlier | Returns the array's primitive value (typically the array itself) | ❌ No |
indexOf() |
ES5 | Searches from start, returns index or -1 if not found | ❌ No |
lastIndexOf() |
ES5 | Searches from end, returns index or -1 if not found | ❌ No |
forEach() |
ES5 | Executes callback for each element; no return value | ❌ No |
map() |
ES5 | Executes callback, returns new array of results | ❌ No |
filter() |
ES5 | Returns array of elements passing callback test | ❌ No |
every() |
ES5 | Checks if all elements pass test; returns boolean | ❌ No |
some() |
ES5 | Checks if any element passes test; returns boolean | ❌ No |
reduce() |
ES5 | Reduces array to single value (left to right) | ❌ No |
reduceRight() |
ES5 | Reduces array to single value (right to left) | ❌ No |
Detailed Method Explanations
1. concat()
Merges one or more arrays or values into a new array, leaving original arrays unchanged.
Parameters: concat(data1, data2, ...) - Optional arrays/values to merge.
const baseArray = [1, 2, 3];
const copyArray = baseArray.concat();
console.log(baseArray); // [1, 2, 3] - original unchanged
console.log(baseArray === copyArray); // false - new reference
console.log(baseArray.concat("hello", "world")); // [1,2,3,"hello","world"]
console.log(baseArray.concat(["x","y"], [[4,5], {name: "user"}]));
// [1,2,3,"x","y",[4,5],{name: "user"}]
2. join()
Converts elements to a string separated by a delimiter (defaults to comma).
Parameters: join(delimiter) - Optional string to separate elements.
const numArray = [1, 2, 3];
console.log(numArray.join()); // "1,2,3"
console.log(numArray.join("-")); // "1-2-3"
console.log(numArray); // [1,2,3] - original unchanged
3. pop()
Removes and returns the last element of the array. Parameters: None
const numArray = [1, 2, 3];
console.log(numArray.pop()); // 3
console.log(numArray); // [1,2] - original mutated
4. shift()
Removes and returns the first element of the array. Parameters: None
const numArray = [1, 2, 3];
console.log(numArray.shift()); // 1
console.log(numArray); // [2,3] - original mutated
5. unshift()
Adds elements to the start of the array and returns the new length.
Parameters: unshift(element1, element2, ...) - Elements to add.
const fruitArr = ["apple", "banana"];
const newLength = fruitArr.unshift("orange");
console.log(newLength); // 3
console.log(fruitArr); // ["orange", "apple", "banana"]
6. push()
Adds elements to the end of the array and returns the new length.
Parameters: push(element1, element2, ...) - Elements to add.
const fruitArr = ["apple", "banana"];
const newLength = fruitArr.push("cherry");
console.log(newLength); // 3
console.log(fruitArr); // ["apple", "banana", "cherry"]
7. reverse()
Reverses the order of elements in the array. Parameters: None
const numArray = [1, 2, 3];
console.log(numArray.reverse()); // [3,2,1]
console.log(numArray); // [3,2,1] - original mutated
8. slice()
Extracts a subset of elements into a new array (does not mutate original).
Parameters: slice(startIndex, endIndex) - startIndex (required) is starting position; endIndex (optional) is end position (exclusive). Negative values count from end.
const nameArr = ["Alice", "Bob", "Charlie", "Diana", "Eve"];
console.log(nameArr.slice(1,3)); // ["Bob", "Charlie"]
console.log(nameArr.slice(-3)); // ["Charlie", "Diana", "Eve"]
console.log(nameArr); // Original array unchanged
9. sort()
Sorts array elements (default: lexicographical order). Mutates original array.
Parameters: sort(comparator) - Optional callback to define sort order.
const numArray = [6, 1024, 52, 256];
console.log(numArray.sort()); // [1024, 256, 52, 6] - lex order
console.log(numArray.sort((a,b) => a - b)); // [6,52,256,1024] - numeric ascending
console.log(numArray); // Sorted array (mutated)
10. splice()
Removes, replaces, or adds elements in place; returns removed elements.
Parameters: splice(start, deleteCount, element1, ...)
const nameArr = ["Alice", "Bob", "Charlie", "Diana"];
// Remove 2 elements starting at index 2
console.log(nameArr.splice(2,2)); // ["Charlie", "Diana"]
console.log(nameArr); // ["Alice", "Bob"]
// Add elements without removing
nameArr.splice(1,0,"Eve","Frank");
console.log(nameArr); // ["Alice", "Eve", "Frank", "Bob"]
11. toString()
Converts array to a comma-separated string (implicitly called during type conversion). Parameters: None
const numArray = [1,2,3];
console.log(numArray.toString()); // "1,2,3"
console.log(numArray); // Original array unchanged
12. valueOf()
Returns the array's primitive value (typically the array itself, used internally by JS). Parameters: None
const numArray = [1,2,3];
console.log(numArray.valueOf()); // [1,2,3]
console.log(numArray.valueOf() === numArray); // true
13. indexOf()
Searches for a value from the start of the array; returns index or -1 if not found.
Parameters: indexOf(value, start) - value to search for; start (optional) is starting position.
const charArr = ["h","e","l","l","o"];
console.log(charArr.indexOf("l")); // 2
console.log(charArr.indexOf("l",3)); //3
console.log(charArr.indexOf("z")); //-1
14. lastIndexOf()
Searches for a value from the end of the array; returns index or -1 if not found.
Parameters: lastIndexOf(value, start) - value to search for; start (optional) is starting position.
const charArr = ["h","e","l","l","o"];
console.log(charArr.lastIndexOf("l")); //3
console.log(charArr.lastIndexOf("l",2)); //2
15. forEach()
Executes a callback function for each element in the array; no return value.
Parameters: forEach((value, index, array) => { ... })
const nameArr = ["Alice", "Bob", "Charlie"];
nameArr.forEach((val, idx, arr) => {
console.log(`${val} is at index ${idx}`);
});
// Logs: Alice is at index 0, Bob at 1, Charlie at 2
16. map()
Executes a callback for each element, returns a new array of callback results.
Parameters: map((value, index, array) => { ... })
const numArray = [1,2,3];
const doubledArray = numArray.map(val => val *2);
console.log(doubledArray); // [2,4,6]
console.log(numArray); // Original unchanged
17. filter()
Returns a new array containing elements that pass the callback's test.
Parameters: filter((value, index, array) => { ... })
const numArray = [1,2,3,4,5,6];
const evenNumbers = numArray.filter(val => val %2 ===0);
console.log(evenNumbers); // [2,4,6]
18. every()
Checks if all elements pass the callback's test; returns boolean.
Stops iteration early if any element fails.
Parametesr: every((value, index, array) => { ... })
const numArray = [2,4,6,8];
console.log(numArray.every(val => val %2 ===0)); // true
console.log(numArray.every(val => val >5)); // false
19. some()
Checks if any element passes the callback's test; returns boolean.
Stops iteration early if any element passes.
Parameters: some((value, index, array) => { ... })
const numArray = [1,3,5,8];
console.log(numArray.some(val => val %2 ===0)); // true (8 is even)
console.log(numArray.some(val => val >10)); // false
20. reduce()
Reduces array to a single value by executing a callback from left to right.
Parameters: reduce((accumulator, currentValue, index, array) => { ... }, initialValue)
const numArray = [10,20,30];
const sum = numArray.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 60
// Without initialValue: uses first element as initial acc
const product = numArray.reduce((acc,curr) => acc * curr);
console.log(product); // 6000
21. reduceRight()
Reduces array to a single value by executing a callback from right to left.
Parameters: Same as reduce()
const strArr = ["a","b","c"];
const reversedStr = strArr.reduceRight((acc, curr) => acc + curr, "");
console.log(reversedStr); // "cba"