Creating and modifying arrays
What is an Array?
An array is a special variable that can hold multiple values at once, organized in an ordered collection.
Each value is called an element, and each has a numeric index starting from 0.
By the end of this lesson, you’ll be able to create, modify, and query arrays using common methods. If you want to deepen your practice, explore the Loops and Iteration lesson to see how loops work with arrays.
1. Creating Arrays
Using Square Brackets
let fruits = [“apple”, “banana”, “cherry”];
console.log(fruits); // [“apple”, “banana”, “cherry”]
- The most common and simple method.
Using the Array Constructor
let numbers = new Array(1, 2, 3, 4);
console.log(numbers); // [1, 2, 3, 4]
Creating Empty Arrays
let emptyArray = [];
let anotherEmpty = new Array();
- Useful when you plan to add items later.
2. Modifying Arrays
Adding Elements
.push() — Add to End
fruits.push(“date”);
console.log(fruits); // [“apple”, “banana”, “cherry”, “date”]
.unshift() — Add to Start
fruits.unshift(“avocado”);
console.log(fruits); // [“avocado”, “apple”, “banana”, “cherry”, “date”]
Removing Elements
.pop() — Remove from End
fruits.pop();
console.log(fruits); // [“avocado”, “apple”, “banana”, “cherry”]
.shift() — Remove from Start
fruits.shift();
console.log(fruits); // [“apple”, “banana”, “cherry”]
Updating Elements
Access by index and reassign:
fruits[1] = “blueberry”;
console.log(fruits); // [“apple”, “blueberry”, “cherry”]
Arrays are mutable — you can change them directly!
Inserting, Deleting, or Replacing with .splice()
.splice(startIndex, deleteCount, item1, item2, …)
Example:
fruits.splice(1, 1, “blackberry”, “kiwi”);
console.log(fruits); // [“apple”, “blackberry”, “kiwi”, “cherry”]
- Start at index 1.
- Remove 1 item.
- Insert “blackberry” and “kiwi” at that position.
Other Useful Array Methods
| Method | Purpose | Example |
|---|---|---|
| .length | Get number of elements | fruits.length |
| .concat() | Merge arrays | array1.concat(array2) |
| .slice() | Copy part of an array | fruits.slice(1, 3) |
| .indexOf() | Find position of an element | fruits.indexOf(“apple”) |
| .includes() | Check if element exists | fruits.includes(“banana”) |
| .reverse() | Reverse the array | fruits.reverse() |
| .sort() | Sort array alphabetically or numerically | fruits.sort() |
Quick Summary:
| Creating Arrays | Modifying Arrays |
|---|---|
|
[] or new Array()
let colors = [‘red’, ‘green’, ‘blue’];
let numbers = new Array(1, 2, 3);
|
.push(),
.pop(), .shift(), .unshift(), .splice() fruits.push(‘orange’); // adds to end
fruits.pop(); // removes from end
|
|
Holds multiple values of any type
Can contain strings, numbers, objects, even other arrays
|
Add, remove, and update elements easily
Methods modify the original array (except slice)
|
|
Index starts from 0
let first = colors[0]; // ‘red’
|
Use index to access or modify
colors[1] = ‘yellow’; // modifies second item
|
Would you also like a quick diagram showing how an array grows and shrinks as we add and remove elements?
To see how arrays interact with the DOM and page elements, check the DOM Manipulation course.
Common array methods (push, pop, map, filter, etc.)
Arrays are powerful because they come with built-in methods that make manipulating data easy and efficient.
1. Push() — Add to End
Adds one or more elements to the end of an array.
let fruits = [“apple”, “banana”];
fruits.push(“cherry”);
console.log(fruits); // [“apple”, “banana”, “cherry”]
- push() returns the new length of the array.
2. Pop() — Remove from End
Removes the last element from an array.
fruits.pop();
console.log(fruits); // [“apple”, “banana”]
- pop() returns the removed element.
3. Unshift() — Add to Start
Adds one or more elements to the beginning of an array.
fruits.unshift(“mango”);
console.log(fruits); // [“mango”, “apple”, “banana”]
4. Shift() — Remove from Start
Removes the first element from an array.
fruits.shift();
console.log(fruits); // [“apple”, “banana”]
5. Map() — Transform Each Element
Creates a new array by applying a function to each element of the array.
let numbers = [1, 2, 3];
let squared = numbers.map(num => num * num);
console.log(squared); // [1, 4, 9]
Does not change the original array.
6. Filter() — Filter Elements
Creates a new array with elements that pass a test (return true).
let ages = [10, 20, 18, 25];
let adults = ages.filter(age => age >= 18);
console.log(adults); // [20, 18, 25]
7. Reduce() — Reduce to Single Value
Applies a function against an accumulator and each element to reduce the array to a single value.
let total = [1, 2, 3, 4].reduce((sum, num) => sum + num, 0);
console.log(total); // 10
8. Find() — Find First Match
Returns the first element that matches a condition.
let users = [{name: “Alice”}, {name: “Bob”}];
let user = users.find(u => u.name === “Bob”);
console.log(user); // {name: “Bob”}
9. FindIndex() — Find First Matching Index
Returns the index of the first element that matches the condition.
let numbers = [5, 12, 8, 130];
let index = numbers.findIndex(num => num > 10);
console.log(index); // 1
10. Includes() — Check Existence
Checks if an array includes a certain element.
let colors = [“red”, “green”, “blue”];
console.log(colors.includes(“green”)); // true
11. Sort() — Sort Elements
Sorts the elements in place.
let nums = [3, 1, 4, 1, 5];
nums.sort();
console.log(nums); // [1, 1, 3, 4, 5] (default sort treats values as strings!)
For numbers, use a compare function:
nums.sort((a, b) => a – b);
12. Slice() — Copy Part of an Array
Returns a shallow copy of a portion of an array into a new array.
let arr = [“a”, “b”, “c”, “d”];
let part = arr.slice(1, 3);
console.log(part); // [“b”, “c”]
Original array remains unchanged.
13. Splice() — Add/Remove/Replace Elements
Modifies the array by adding, removing, or replacing elements.
let arr = [“Jan”, “March”, “April”];
arr.splice(1, 0, “Feb”);
console.log(arr); // [“Jan”, “Feb”, “March”, “April”]
Changes the original array.
Quick Summary Table:
| Method | Purpose | Mutates Array? | Returns New Array? |
|---|---|---|---|
| push() | Add at end | Yes | No |
| pop() | Remove from end | Yes | No |
| shift() | Remove from start | Yes | No |
| unshift() | Add at start | Yes | No |
| map() | Transform each item | No | Yes |
| filter() | Select matching items | No | Yes |
| reduce() | Reduce to single value | No | Yes |
| find() | Find first matching element | No | (Single item) |
| includes() | Check if value exists | No | (true/false) |
| sort() | Sort elements | Yes | No |
| slice() | Copy a portion of array | No | Yes |
| splice() | Add/remove/replace elements | Yes | No (returns removed items) |
Bonus Tip
You can chain many methods together:
let result = [1, 2, 3, 4, 5]
.filter(n => n % 2 === 0)
.map(n => n * n);
console.log(result); // [4, 16]
Filter even numbers, then square them.
Object creation and manipulation
What is an Object?
An object is a collection of key-value pairs, where the keys (also called properties) are strings (or Symbols), and the values can be any type: string, number, boolean, function, another object, etc.
Objects allow you to group related data and behavior together.
1. Creating Objects
Object Literal (Most Common Way)
const person = {
name: “Alice”,
age: 25,
isStudent: true
};
Simple and readable.
Using the new Object() Syntax
const person = new Object();
person.name = “Bob”;
person.age = 30;
Works, but less preferred than literals for most cases.
Using a Constructor Function
function Person(name, age) {
this.name = name;
this.age = age;
}
const person1 = new Person(“Charlie”, 28);
Useful for creating multiple similar objects.
Using Classes (Modern ES6+)
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const person2 = new Person(“Daisy”, 22);
Cleaner syntax for object “blueprints.
For deeper coverage of ES6 classes and object-oriented patterns, see the Advanced JavaScript Concepts course.
2. Accessing Object Properties
Dot Notation
console.log(person.name); // “Alice”
Bracket Notation
console.log(person[“age”]); // 25
Use basics and Syntax to understand how bracket notation interacts with dynamic property access and variables.




