Detailed explanations & code examples are in the JavaScript (.js) file
Click the { } button at the bottom right to view it
Open the browser console (F12) to see all outputs!
Arrays store multiple values in a single variable
let fruits = ["apple", "orange", "banana"];| Method | Description | Example |
|---|---|---|
| .push(element) | Adds element to END | fruits.push("mango") |
| .pop() | Removes LAST element | fruits.pop() |
| .unshift(element) | Adds element to BEGINNING | fruits.unshift("mango") |
| .shift() | Removes FIRST element | fruits.shift() |
| .length | Returns number of elements | fruits.length |
| .indexOf(element) | Returns index of element | fruits.indexOf("banana") |
| .sort() | Sorts array alphabetically | fruits.sort() |
| .reverse() | Reverses array order | fruits.reverse() |
for(let i = 0; i < fruits.length; i++)for(let fruit of fruits) ← Cleaner!
2D arrays store data in rows and columns (like a grid or table)
const matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];matrix[row][column]matrix[0][0] = 1, matrix[1][2] = 6
Tic-Tac-Toe Example: Can replace numbers with 'X' and 'O'
The spread operator expands an array or string into separate elements
...arrayName| Use Case | Code | Result |
|---|---|---|
| Function Arguments | Math.max(...[1,2,3,4,5]) |
5 |
| Spread String | [..."Umer"] |
['U', 'm', 'e', 'r'] |
| Combine Arrays | [...arr1, ...arr2] |
One merged array |
Rest parameters bundle multiple arguments into an array
...arrayfunction(...params)
function myFunction(...params){
// params is now an array of all arguments
}
| Example | Function | Description |
|---|---|---|
| Example 1 | getFood(...foods) |
Returns array of all food arguments |
| Example 2 | sum(...numbers) |
Sums any number of arguments |
| Example 2 | getAverage(...numbers) |
Calculates average of any numbers |
| Example 3 | combineStrings(...strings) |
Joins any number of strings |
A callback is a function passed as an argument to another function
function hello(callback){
console.log("Hello!");
callback(); // Calls the function passed in
}
function goodbye(){
console.log("Goodbye!");
}
hello(goodbye); // Pass goodbye as argument
Loading...