JavaScript Day 6: Objects, Arrays & Array Methods

Introduction

Day 6 of your JavaScript adventure! We are going to discuss two of the most basic and most powerful data structures in programming today: Objects and Arrays. Imagine objects as digital boxes containing similar information (such as the profile of a person with name, age, and hobbies), and arrays as lists (such as a shopping list or a playlist).

Why are Objects and Arrays so important?

In practice, you always deal with structured data:

  • Objects assist you in grouping similar information (user profiles, product details, configuration settings) together.
  • Arrays allow you to handle groups of objects (list of users, shopping cart items, search results).
  • The array methods offer effective means to manipulate data (add, remove, search, transform).

It is important to understand these concepts since:

  • They are the basis of data management in JavaScript.
  • All APIs you deal with give return objects or arrays.
  • These structures are essential to modern frameworks (React, Vue, Angular).
  • They ensure that your code is organized, readable and maintainable.

At the conclusion of this tutorial, you will be able to create objects using methods, access properties in various ways, and manipulate data using powerful array methods like a pro!

Step-by-Step Tutorial

Step 1: Setting Up Your HTML Structure

We will begin with a basic HTML page to show our JavaScript output:

🌐
 <title>Day 6 - Objects & Arrays</title>
    
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 40px auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        p {
            background: white;
            padding: 15px;
            border-left: 4px solid #3498db;
            margin: 15px 0;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
    


    <h1>JavaScript Objects & Arrays Demo</h1>
    <h2>Check the Console (F12) for detailed output!</h2>
    
    <h3>Object Example:</h3>
    <p id="car"></p>
    
    <h3>Object with Getters/Setters:</h3>
    <p id="demo"></p>
    
    


What this does:

  • Produces a clean page layout with styled paragraphs.
  • Offers two dummy objects (car and demo) to show object data.
  • External JavaScript file links to ensure clean separation of concerns.
  • Adds simple CSS to enhance visual display.

Pro Tip: You should always open your browser Developer Console (F12) to view console.log() outputs. It is here that we learn the majority of things!

Step 2: Creating Your First Object - A Car

Objects consist of related properties (data) and methods (functions). We will make a basic car object:

🎨
let car = { 
    type: "volvo", 
    color: "white", 
    weight: 900 
};

document.getElementById("car").innerHTML = "Car: " + car.type;

How it works:

  • { } – Curly braces create an object
  • type: “volvo” – Property name (key) and value pairs
  • Properties are separated by commas
  • We access properties using dot notation: car.type

Two ways to access properties:

console.log(car.type);        // Dot notation (most common)

console.log(car[“color”]);    // Bracket notation (useful for dynamic keys)

When to use bracket notation:

  • In case of spaces or special characters in property names.
  • This occurs when property names are stored in variables.
  • In dynamically accessing properties in loops.

Note: The names of the object properties are referred to as keys, and the data they contain are referred to as values. They are collectively known as key-value pairs.

Step 3: Advanced Objects - Getters and Setters

JavaScript enables you to create special properties which behave like functions. These are referred to as getters (read values) and setters (write values):

📄
const obj = { counter: 0 };

// Define a GETTER - reads like a property but runs a function
Object.defineProperty(obj, "reset", {
    get: function () { 
        this.counter = 0; 
    }
});

Object.defineProperty(obj, "Increment", {
    get: function () { 
        this.counter++; 
    }
});

Object.defineProperty(obj, "Decrement", {
    get: function () { 
        this.counter--; 
    }
});

// Define SETTERS - accept values
Object.defineProperty(obj, "add", {
    set: function (value) { 
        this.counter += value; 
    }
});

Object.defineProperty(obj, "subtract", {
    set: function (value) { 
        this.counter -= value; 
    }
});

// Using the getters and setters
obj.reset;           // Calls the reset getter (sets counter to 0)
obj.add = 6;        // Calls the add setter (counter becomes 6)
obj.subtract = 1;   // Calls subtract setter (counter becomes 5)
obj.Increment;      // Calls Increment getter (counter becomes 6)
obj.Decrement;      // Calls Decrement getter (counter becomes 5)

document.getElementById("demo").innerHTML = obj.counter;  // Displays: 5

Understanding the flow:

  1. Reset: Counter = 0
  2. Add 6: Counter = 0 + 6 = 6
  3. Subtract 1: Counter = 6 – 1 = 5
  4. Increment: Counter = 5 + 1 = 6
  5. Decrement: Counter = 6 – 1 = 5

Why use getters and setters?

  • Encapsulation – Hide internal logic behind simple property access.
  • Validation – Check values prior to setting them.
  • Computed properties – Compute values dynamically.
  • Cleaner syntax – obj.reset is cleaner than obj.reset()

Notice: It is important to note that getters are called without parentheses (obj.reset, not obj.reset()) and setters are called with the assignment operator (obj.add = 6).

Step 4: Creating a Rich Person Object with Methods

We will create a full object with different data types and functions:

📄
const person = {
    // Simple properties
    firstName: "Niotechone",
    lastName: "Technology",
    age: 22,
    
    // Array property
    hobbies: ["reading", "coding", "traveling"],
    
    // Method: function inside an object
    fullName: function () {
        return this.firstName + " " + this.lastName + " " + this.age + " " + this.hobbies;
    },
    
    // Another method
    greet: function () {
        return "Hello, my name is " + this.fullName() + ".";
    }
};

Understanding this keyword:

  • Inside an object method, this refers to the object itself
  • this.firstName refers to the firstName property of this object.
  • It enables access to other properties and methods of the same object.

Pro Tip: This can be thought of as saying my own – such as my own firstName or my own fullName method.

Step 5: Accessing Object Properties

Object data can be worked with in several ways:

🎨
// Dot notation (most common and readable)
console.log(person.firstName);        // Output: "Niotechone"

// Bracket notation (useful for variables or special characters)
console.log(person["lastName"]);      // Output: "Technology"

// Accessing simple properties
console.log(person.age);              // Output: 22

// Accessing array elements within objects
console.log(person.hobbies[1]);       // Output: "coding"

When to use each method:

Method

Use Case

Example

Dot notation

Known property names, no spaces

person.firstName

Bracket notation

Dynamic properties, variables, spaces

person[“first name”] or person[key]

Step 6: Calling Object Methods

Methods are functions that are stored as object properties. They may use this to access other properties:

📄
// Calling methods - note the parentheses!
console.log(person.fullName());       
// Output: "Niotechone 22 reading,coding,traveling"

console.log(person.greet());          
// Output: "Hello, my name is Niotechone 22 reading,coding,traveling."

Key difference:

  • Properties (data): Access without parentheses → person.firstName
  • Methods (functions): Call with parentheses → person.fullName()

Note: The greet() method calls the fullName() method. This shows how techniques can collaborate in an object!

Step 7: Working with Arrays - The Basics

Arrays are ordered lists which may contain any type of data. Let’s create and manipulate one:

📄
// Create an array
let fruits = ["apple", "banana", "cherry"];
console.log("Initial:", fruits);
// Output: ["apple", "banana", "cherry"]

Array characteristics:

  • Sequential (elements are in a particular order)
  • Zero-indexed (first element is at position 0)
  • Is capable of storing any type of data (strings, numbers, objects, even other arrays)
  • Dynamic size (can expand or contract)

Step 8: Array Method - push() (Add to End)

The push() method will insert one or more items at the end of an array:

📄
fruits.push("mango");

console.log("After push:", fruits);

// Output: ["apple", "banana", "cherry", "mango"]

How it works:

  • Takes one or more arguments
  • Adds them to the end of the array
  • Modifies the original array (mutating method)
  • Returns the new array length.

Real-life example: Adding items to a shopping cart, appending messages to a chat, adding tasks to a to-do list.

Step 9: Array Method - pop() (Remove from End)

The pop() function deletes the last element from an array:

📄
fruits.pop();
console.log("After pop:", fruits);
// Output: ["apple", "banana", "cherry"]

How it works:

  • Removes the last element
  • Modifies the original array
  • Returns the removed element
  • Takes no arguments

 

Pro Tip: You can store the element that was removed: let removed = fruits.pop();

Step 10: Array Method - unshift() (Add to Start)

The unshift() method inserts one or more items at the start of an array:

📄
fruits.unshift("lemon");
console.log("After unshift:", fruits);
// Output: ["lemon", "apple", "banana", "cherry"]

How it works:

  • Inserts elements at the front (index 0)
  • Moves all the existing elements to greater indexes.
  • Modifies the original array
  • Returns the new length

Performance note: unshift() is slower than push() since it has to re-index all the existing elements.

Step 11: Array Method - shift() (Remove from Start)

The shift() method takes the first element out of an array:

📄
fruits.shift();
console.log("After shift:", fruits);
// Output: ["apple", "banana", "cherry"]

How it works:

  • Removes the first element (index 0)
  • Moves everything that is left one step down.
  • Modifies the original array
  • Returns the removed element

     

Memory trick:

  • push/pop → Work on the END (like a stack)
  • unshift/shift → Work on the START

Step 12: Array Method - splice() (Remove & Insert)

The splice() method is the Swiss Army knife of array manipulation – it can delete, replace, and add elements:

📄
fruits.splice(1, 1, "kiwi", "orange");
console.log("After splice:", fruits);
// Output: ["apple", "kiwi", "orange", "cherry"]

Syntax breakdown:

array.splice(startIndex, deleteCount, item1, item2, …)

  • startIndex (1): Starting point of modification.
  • deleteCount (1): The number of elements to delete.
  • item1, item2… (“kiwi”, “orange”): Items to be inserted.


What happened:

  • Started at index 1 (which was “banana”)
  • Removed 1 element (“banana”)
  • Inserted “kiwi” and “orange” at that position

Common uses:

  • splice(2, 1) – Remove 1 element at index 2
  • splice(1, 0, “new”) – Insert “new” at index 1 without removing anything
  • splice(0, 2) – Remove first 2 elements.

Notice: splice() alters the original array and gives an array of deleted elements.

Step 13: Array Method - slice() (Copy Portion)

The slice() method is used to make a shallow copy of a section of an array without altering the original:

🎨
let citrus = fruits.slice(1, 3);
console.log("Sliced:", citrus);
// Output: ["kiwi", "orange"]

console.log("Original unchanged:", fruits);
// Output: ["apple", "kiwi", "orange", "cherry"]

Syntax:

array.slice(startIndex, endIndex)

  • startIndex (1): Where to start copying (inclusive)
  • endIndex (3): Where to stop copying (exclusive – not included)


Key differences from splice:

Feature

splice()

slice()

Modified original?

Yes

No

Can I insert?

Yes

No

Returns

Removed elements

Copied elements

Pro Tip: slice() is the method to use when you need to keep the original array and operate with a copy!

Step 14: Array Method - indexOf() (Find Position)

The indexOf() method gives the first index of a given element:

🎨
console.log("Index of kiwi:", fruits.indexOf("kiwi"));
// Output: 1

How it works:

  • Searches from left to right
  • Returns the index if found
  • Returns -1 if not found
  • Compared using strict equality (===).

     

Practical example:

🎨
if (fruits.indexOf("banana") !== -1) {

    console.log("Banana is in the array!");

} else {

    console.log("Banana not found!");

}

Step 15: Array Method - includes() (Check Existence)

The includes() method is used to determine whether an array has a certain element and it returns a boolean:

🎨
console.log("Has a banana?", fruits.includes("banana"));

// Output: false

console.log("Has apple?", fruits.includes("apple"));

// Output: true

Why use includes() over indexOf()?

🎨
// Old way (harder to read)

if (fruits.indexOf("apple") !== -1) { }

// Modern way (cleaner)

if (fruits.includes("apple")) { }

Benefits:

  • More readable and intuitive
  • Directly returns a boolean (no comparison with -1 required)
  • Better expresses intent

     

Note: includes() is typically used when you want to do a simple existence check, whereas indexof() is more appropriate when you want to know the actual position.

Step 16: Array Property - length

Each array has a length property which informs you of the number of elements it contains:

🎨
console.log("Length:", fruits.length);
// Output: 4 (for ["apple", "kiwi", "orange", "cherry"])

Common uses:

🎨
// Loop through all elements
for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

// Check if array is empty
if (fruits.length === 0) {
    console.log("Array is empty!");
}

// Get the last element
let lastFruit = fruits[fruits.length - 1];

// Remove all elements (empty the array)
fruits.length = 0;

Warning: Setting length to a smaller value truncates the array, permanently removing elements!

Step 17: Complete Real-World Example - Student Object

Now we will put all we have learned into practice:

🎨
let student = {
    name: "Anita",
    age: 20,
    subjects: ["Math", "Science", "English"],
    
    introduce: function () {
        return `Hi, I'm ${this.name} and I study ${this.subjects.join(", ")}.`;
    }
};

// Accessing properties
console.log(student.name);           // Output: "Anita"

// Accessing array element within object
console.log(student.subjects[1]);    // Output: "Science"

// Calling method
console.log(student.introduce());    
// Output: "Hi, I'm Anita and I study Math, Science, English."

What’s new here:

Template literals (Hi, I am ${this.name})

  • Quotes should be replaced with backticks.
  • Embed variables with ${}
  • Less dirty than string concatenation.

     

Array join() method

  • subjects.join(“ ,” ) turns an array into a string.
  • Inserts “, ” between elements
  • Result: “Math, Science, English”

     

This is a very widespread pattern in practice:

  • Multi-data field user profiles.
  • Specified product objects.
  • Tagged/categorized blog posts.
  • Shopping cart properties.

Tables of Key Concepts

1. Objects & Arrays Components

Name

Description

Object

Collection of key-value pairs (properties) and methods

Property

A variable stored inside an object (key-value pair)

Method

A function stored inside an object

this

Keyword that refers to the current object

Array

Ordered, indexed collection of elements

Index

Numeric position of an element in an array (starts at 0)

Getter

Property that runs a function when accessed

Setter

Property that runs a function when assigned a value

Dot notation

Accessing properties using object.property

Bracket notation

Accessing properties using object[“property”]

Object.defineProperty()

Method to define getters/setters on an object

Template literals

String syntax using backticks with ${} for variables

2. Key Array Methods & Properties

Method/Property

Description

Modified Original?

Returns

push(item)

Adds element(s) to end of array

Yes

New length

pop()

Removes last element

Yes

Removed element

unshift(item)

Adds element(s) to beginning

Yes

New length

shift()

Removes first element

Yes

Removed element

splice(start, count, items)

Removes/inserts elements at position

Yes

Array of removed elements

slice(start, end)

Copies portion of array

No

New array (copy)

indexOf(item)

Finds first index of element

No

Index or -1

includes(item)

Checks if element exists

No

Boolean (true/false)

join(separator)

Converts array to string

No

String

.length

Number of elements in array

Number

Summary

Day 6 is dedicated to learning how to work with two fundamental JavaScript data structures Objects and Arrays, as well as the powerful array methods that you will use every day as a developer. You get to know how objects store information in pairs of keys and values and how methods within an object use this to communicate with other properties. Next you study arrays- ordered lists with many applications in real life- and get to know how to add, remove, search, and copy objects with functions such as push, pop, shift, unshift, splice, slice, index of, includes and others. At the conclusion of this lesson, you know how to organize the information properly, how to work with lists effectively, and how these tools are the basis of APIs work, UI elements, and current frameworks such as React and Angular.

Output

JavaScript Day 6 tutorial covering objects, arrays, and essential array methods for beginners

Frequently Asked Questions FAQs

An object is used to store data in pairs of keys and values and an array is used to store items in a list in order (0, 1, 2...). Structured details are best represented as objects, lists are represented as arrays.

When the name of the property is known and it does not contain any spaces, use dot notation.

When dynamic keys, variables, or property names are used and include spaces, bracket notation should be used.

Yes. Push, pop, shift, unshift, and splice are some of the methods that alter the original array.

The array is not altered by such methods as slice() and index of.

this is the current object and one method can access other properties or methods within the same object.

splice alters the initial array by eliminating or adding elements.

slice() is a function that gives a duplicate of a part of the array and does not modify the original.