Arrays and Objects

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.

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?

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.

2. Accessing Object Properties

Dot Notation

console.log(person.name); // “Alice”

Bracket Notation

console.log(person[“age”]); // 25

Use bracket notation if the property name is stored in a variable or is dynamic.

3. Modifying Object Properties

You can change the value of a property:

person.age = 26;
console.log(person.age); // 26

Just reassign using dot or bracket notation.

4. Adding New Properties

You can add new properties at any time:

person.city = “New York”;
console.log(person.city); // “New York”

5. Deleting Properties

Use the delete keyword:

delete person.isStudent;
console.log(person.isStudent); // undefined

Property is completely removed.

6. Common Object Methods

Method Purpose Example
Object.keys(obj) Returns array of keys Object.keys(person)
Object.values(obj) Returns array of values Object.values(person)
Object.entries(obj) Returns array of [key, value] pairs Object.entries(person)
Object.assign(target, source) Copies properties Object.assign({}, person)
hasOwnProperty(key) Checks if property exists person.hasOwnProperty(“name”)

Example: Full Object Operations

const car = {
brand: “Toyota”,
model: “Camry”,
year: 2022
};

// Accessing
console.log(car.brand); // “Toyota”

// Modifying
car.year = 2023;

// Adding
car.color = “blue”;

// Deleting
delete car.model;

// Checking
console.log(car.hasOwnProperty(“model”)); // false

// Listing Keys
console.log(Object.keys(car)); // [“brand”, “year”, “color”]

// Listing Values
console.log(Object.values(car)); // [“Toyota”, 2023, “blue”]

// Entries (Pairs)
console.log(Object.entries(car));
// [[“brand”, “Toyota”], [“year”, 2023], [“color”, “blue”]]

Quick Summary:

Action How to Do It
Create {} or new Object()
Access object.property or object[“property”]
Modify object.property = newValue
Add object.newProperty = value
Delete delete object.property
Copy properties Object.assign()
List keys/values Object.keys(), Object.values()

Object methods and this keyword

What is an Object Method?

A method is simply a function that belongs to an object.

It defines behavior for that object — meaning it can perform actions using the object’s own data.

Syntax:

const person = {
name: “Alice”,
greet: function() {
console.log(“Hello, ” + this.name);
}
};

person.greet(); // “Hello, Alice”

  • greet is a method.
  • It uses this.name to refer to the name property of the same object.

1. Defining Object Methods

Traditional Function Syntax

const car = {
brand: “Toyota”,
start: function() {
console.log(this.brand + ” is starting…”);
}
};

car.start(); // “Toyota is starting…”

ES6 Method Shorthand (Recommended)

const car = {
brand: “Toyota”,
start() {
console.log(this.brand + ” is starting…”);
}
};
car.start(); // “Toyota is starting…”

Cleaner and shorter.

What is this?

this refers to the object that is calling the method.

  • Inside a method, this automatically points to the object the method belongs to.
  • this gives you access to other properties and methods inside the same object.

Important Note About this

  • In regular functions inside an object, this works normally.
  • In arrow functions, this does NOT bind to the object — it binds to the outer scope.

Example:

const user = {
name: “Bob”,
greet: () => {
console.log(“Hi, ” + this.name);
}
};

user.greet(); // “Hi, undefined”

  • Arrow functions do not have their own this.
  • Avoid using arrow functions for methods!

Practical Example:

const user = {
username: “supercoder”,
getUsername() {
return this.username;
}
};

console.log(user.getUsername()); // “supercoder”

2. Adding Methods After Object Creation

You can add methods later dynamically:

user.sayHello = function() {
console.log(“Hello, ” + this.username);
};

user.sayHello(); // “Hello, supercoder”

3. Using this to Link Properties and Methods

Example with a product:

const product = {
name: “Laptop”,
price: 1500,
getDetails() {
return `${this.name} costs $${this.price}`;
}
};

console.log(product.getDetails()); // “Laptop costs $1500”

Quick Summary Table:

Concept Explanation
Object Method Function inside an object
this Keyword Refers to the object that calls the method
Arrow Functions Do NOT bind their own this
Method Shorthand Cleaner way to define functions inside objects (ES6)
Dynamic Method Methods can be added to objects even after creation

Bonus Tip: Nested Objects and this

In nested objects, be careful — this refers to the immediate calling object.

Example:

const outer = {
inner: {
value: 42,
show() {
console.log(this.value);
}
}
};

outer.inner.show(); // 42

Here, this refers to inner, not outer.

Destructuring and spread/rest operators

What is Destructuring?

Destructuring is a convenient way to unpack values from arrays or properties from objects into separate variables.

Instead of accessing each value manually, you extract them neatly.

1. Array Destructuring

Basic Example:

const colors = [“red”, “green”, “blue”];

const [first, second, third] = colors;
console.log(first); // “red”
console.log(second); // “green”
console.log(third); // “blue”

Order matters in arrays!

Skipping Items:

const [primary, , tertiary] = colors;
console.log(primary); // “red”
console.log(tertiary); // “blue”

Default Values:

const [a, b, c = “yellow”] = [“pink”];
console.log(a); // “pink”
console.log(b); // undefined
console.log(c); // “yellow”

2. Object Destructuring

Basic Example:

const person = {
name: “Alice”,
age: 25
};

const { name, age } = person;
console.log(name); // “Alice”
console.log(age); // 25

Order does not matter in objects (key names must match).

Renaming Variables:

const { name: username, age: userAge } = person;
console.log(username); // “Alice”
console.log(userAge); // 25

Default Values:

const { city = “Unknown” } = person;
console.log(city); // “Unknown”

Rest Operator (…)

Rest syntax … collects multiple elements into a single array or object.

1. Rest with Arrays

Gather remaining elements:

const [first, …others] = [1, 2, 3, 4];
console.log(first); // 1
console.log(others); // [2, 3, 4]

2. Rest with Objects

Gather remaining properties:

const { name, …rest } = { name: “Sam”, age: 30, city: “London” };
console.log(name); // “Sam”
console.log(rest); // { age: 30, city: “London” }

Quick Summary Table:

Feature Symbol Purpose Example
Array Destructuring Extract values from arrays [a, b] = array
Object Destructuring Extract properties from objects {name} = object
Spread Operator Expand elements/properties […arr1, …arr2] or {…obj1, …obj2}
Rest Operator Collect remaining values/properties const [a, …rest] = array or const {…rest} = obj

Bonus Tip: Spread and Rest Look Same But Act Differently!

  • Spread = expands data
  • Rest = collects data
  • It depends on where you use the … symbol!

Example Using Both Together

function sum(a, b, …rest) {
console.log(a + b); // sum of first two
console.log(rest); // array of remaining arguments
}

sum(1, 2, 3, 4, 5);
// Output:
// 3
// [3, 4, 5]

Leave a Comment