Web Development /JavaScript Programming / Lesson
Web Development

JavaScript Objects, Properties and Methods

Learn how JavaScript objects store structured information using properties and methods, how to create and modify objects, access nested data, work with object arrays, and use modern object techniques in real-world web applications.

🎯

Learning Objectives

["Understand what JavaScript objects are and why they are important.","Create objects using object literal syntax.","Understand properties and values.","Access object properties using dot notation.","Access object properties using bracket notation.","Add, update and delete object properties.","Store different JavaScript data types inside objects.","Create and use methods inside objects.","Understand the role of this inside object methods.","Work with nested objects.","Work with arrays stored inside objects.","Create arrays containing multiple objects.","Use object methods such as Object.keys(), Object.values() and Object.entries().","Understand property existence checks.","Use destructuring to extract object properties.","Use spread syntax to copy and combine objects.","Understand the difference between object references and copied values.","Use objects to model practical application data.","Apply objects in real-world web development projects."]

📖

Lesson Content

Introduction to JavaScript Objects

JavaScript objects are one of the most important concepts in modern web development. Objects allow developers to organize related information and behavior into a single structure.

For example, a student can be represented as an object:

const student = {
    name: "Ade",
    age: 20,
    course: "Web Development"
};

The object contains related information about the student. Each piece of information is stored as a property.

What Is an Object?

An object is a collection of related data stored as key-value pairs.

const student = {
    name: "Ade",
    age: 20,
    course: "Web Development"
};

In this example:

  • name is a property.
  • "Ade" is the value of the name property.
  • age is a property.
  • 20 is the value of the age property.
  • course is a property.
  • "Web Development" is the value of the course property.

Objects are especially useful when several values belong together.

Creating Objects

The most common way to create an object is by using curly braces.

const user = {
    firstName: "Ade",
    lastName: "Johnson",
    email: "ade@example.com"
};

Each property is separated by a comma.

Object Properties

Properties describe the characteristics or data associated with an object.

const course = {
    title: "Web Development",
    duration: 6,
    fee: 150000,
    active: true
};

The values can be different JavaScript data types.

  • String
  • Number
  • Boolean
  • Array
  • Object
  • Function
  • null

Accessing Properties with Dot Notation

Dot notation is the most common way to access an object property.

const student = {
    name: "Ade",
    age: 20,
    course: "Web Development"
};

console.log(student.name);
console.log(student.age);
console.log(student.course);

The output will be:

Ade
20
Web Development

Bracket Notation

Properties can also be accessed using square brackets.

const student = {
    name: "Ade",
    age: 20
};

console.log(student["name"]);
console.log(student["age"]);

Bracket notation becomes particularly useful when the property name is stored inside a variable.

const property = "course";

const student = {
    name: "Ade",
    course: "Web Development"
};

console.log(student[property]);

When to Use Bracket Notation

Bracket notation is useful when working with dynamic property names.

const field = "email";

const user = {
    name: "Ade",
    email: "ade@example.com"
};

console.log(user[field]);

Dot notation would interpret field as the literal property name, while bracket notation evaluates the variable first.

Adding Properties

New properties can be added after an object has been created.

const student = {
    name: "Ade"
};

student.age = 20;
student.course = "Web Development";

console.log(student);

Updating Properties

Existing properties can be updated by assigning a new value.

const student = {
    name: "Ade",
    score: 65
};

student.score = 85;

console.log(student.score);

The score has changed from 65 to 85.

Deleting Properties

The delete operator can remove an object property.

const student = {
    name: "Ade",
    age: 20,
    temporaryCode: "ABC123"
};

delete student.temporaryCode;

console.log(student);

Use deletion carefully in application code because removing properties can affect other parts of a program that expect those properties to exist.

Objects Can Contain Arrays

An object property can contain an array.

const student = {
    name: "Ade",
    courses: [
        "HTML",
        "CSS",
        "JavaScript"
    ]
};

We can access the array:

console.log(student.courses);

We can also access individual array elements:

console.log(student.courses[0]);
console.log(student.courses[2]);

Objects Can Contain Other Objects

Objects can be nested inside other objects.

const student = {
    name: "Ade",
    contact: {
        email: "ade@example.com",
        phone: "08000000000"
    }
};

To access the nested email address:

console.log(student.contact.email);

Nested objects are common when representing structured information from APIs and databases.

Object Methods

An object can contain functions. A function stored as an object property is commonly called a method.

const student = {
    name: "Ade",

    greet: function() {
        console.log("Hello " + this.name);
    }
};

student.greet();

The greet() function is a method of the student object.

Using this

The this keyword can refer to the object that is calling a method.

const student = {
    name: "Ade",

    introduce: function() {
        console.log("My name is " + this.name);
    }
};

student.introduce();

Here, this.name refers to the name property of the student object when the method is called as student.introduce().

Modern Object Method Syntax

Modern JavaScript provides a shorter syntax for defining methods.

const student = {
    name: "Ade",

    introduce() {
        console.log("My name is " + this.name);
    }
};

student.introduce();

This syntax is widely used in modern JavaScript applications.

Objects with Different Data Types

A single object can contain multiple types of data.

const profile = {
    name: "Ade",
    age: 21,
    active: true,
    skills: ["HTML", "CSS", "JavaScript"],
    address: {
        city: "Agbor",
        country: "Nigeria"
    }
};

This makes objects powerful for representing real-world entities.

Arrays of Objects

One of the most common patterns in web development is an array containing multiple objects.

const students = [
    {
        name: "Ade",
        score: 85
    },
    {
        name: "John",
        score: 72
    },
    {
        name: "Mary",
        score: 91
    }
];

We can access the first student:

console.log(students[0]);

We can access the first student’s name:

console.log(students[0].name);

We can access the third student’s score:

console.log(students[2].score);

Combining Objects with Array Methods

Objects and arrays are frequently used together.

const students = [
    { name: "Ade", score: 85 },
    { name: "John", score: 42 },
    { name: "Mary", score: 91 }
];

const passedStudents = students.filter(
    student => student.score >= 50
);

console.log(passedStudents);

We can also extract the names:

const names = students.map(
    student => student.name
);

console.log(names);

Object.keys()

Object.keys() returns an array containing the names of an object’s enumerable properties.

const student = {
    name: "Ade",
    age: 20,
    course: "Web Development"
};

const keys = Object.keys(student);

console.log(keys);

The result is:

["name", "age", "course"]

Object.values()

Object.values() returns an array containing the property values.

const student = {
    name: "Ade",
    age: 20,
    course: "Web Development"
};

const values = Object.values(student);

console.log(values);

Object.entries()

Object.entries() returns an array containing key-value pairs.

const student = {
    name: "Ade",
    age: 20
};

const entries = Object.entries(student);

console.log(entries);

The result is conceptually:

[
    ["name", "Ade"],
    ["age", 20]
]

This can be useful when looping through object properties.

Looping Through Object Properties

The for...in loop can be used to iterate over enumerable property names.

const student = {
    name: "Ade",
    age: 20,
    course: "Web Development"
};

for (const key in student) {
    console.log(key, student[key]);
}

Bracket notation is useful here because the property name is stored in the key variable.

Checking Whether a Property Exists

The in operator can check whether a property exists.

const student = {
    name: "Ade",
    age: 20
};

console.log("name" in student);
console.log("email" in student);

The results are:

true
false

Destructuring Objects

Object destructuring allows us to extract properties into variables.

const student = {
    name: "Ade",
    age: 20,
    course: "Web Development"
};

const { name, age, course } = student;

console.log(name);
console.log(age);
console.log(course);

This can make code shorter and easier to read.

Renaming Destructured Properties

A property can be assigned to a variable with a different name.

const student = {
    name: "Ade",
    score: 85
};

const {
    name: studentName,
    score: studentScore
} = student;

console.log(studentName);
console.log(studentScore);

Default Values with Destructuring

Destructuring can provide a default value when a property is missing.

const student = {
    name: "Ade"
};

const {
    name,
    course = "Web Development"
} = student;

console.log(name);
console.log(course);

Spread Syntax with Objects

Spread syntax can create a new object containing properties from another object.

const student = {
    name: "Ade",
    age: 20
};

const studentCopy = {
    ...student
};

console.log(studentCopy);

Spread syntax can also combine objects.

const personal = {
    name: "Ade",
    age: 20
};

const academic = {
    course: "Web Development",
    score: 85
};

const student = {
    ...personal,
    ...academic
};

console.log(student);

Updating an Object with Spread Syntax

Spread syntax can be used to create a new object while changing selected properties.

const student = {
    name: "Ade",
    score: 65
};

const updatedStudent = {
    ...student,
    score: 90
};

console.log(updatedStudent);

This technique is common in modern JavaScript applications because it avoids directly changing the original object.

Object References

Objects are reference values. Assigning one object variable to another does not create an independent copy.

const student = {
    name: "Ade"
};

const anotherStudent = student;

anotherStudent.name = "John";

console.log(student.name);

The original object is also affected because both variables refer to the same object.

Creating a Shallow Copy

Spread syntax can create a shallow copy.

const student = {
    name: "Ade",
    score: 85
};

const copy = {
    ...student
};

copy.name = "John";

console.log(student.name);
console.log(copy.name);

The two top-level objects are now separate.

Nested Object References

It is important to understand that object spread creates a shallow copy. Nested objects can still share references.

const student = {
    name: "Ade",
    contact: {
        city: "Agbor"
    }
};

const copy = {
    ...student
};

copy.contact.city = "Asaba";

console.log(student.contact.city);

The nested object is shared in this example. More advanced cloning techniques may be required when an application needs completely independent nested structures.

Practical Example: Course Object

A training platform can represent a course using an object.

const course = {
    title: "Web Development",
    duration: "6 Months",
    fee: 150000,
    active: true,

    modules: [
        "HTML",
        "CSS",
        "JavaScript"
    ],

    displayInfo() {
        console.log(
            this.title + " - " + this.duration
        );
    }
};

course.displayInfo();

This object contains both data and behavior.

Practical Example: Student Record

const student = {
    name: "Ade",
    email: "ade@example.com",
    course: "Web Development",
    scores: [75, 82, 91],

    calculateAverage() {
        const total = this.scores.reduce(
            (sum, score) => sum + score,
            0
        );

        return total / this.scores.length;
    }
};

console.log(student.name);
console.log(student.calculateAverage());

This demonstrates how an object can keep related data and functions together.

Objects and JSON

JavaScript objects are closely related to JSON, which is commonly used to exchange data between websites, APIs and servers.

A JavaScript object may look like:

const user = {
    name: "Ade",
    age: 20
};

JSON uses a similar structure:

{
    "name": "Ade",
    "age": 20
}

JSON is a text-based data format, while a JavaScript object is an in-memory JavaScript value.

Converting Objects to JSON

JSON.stringify() converts a JavaScript value into a JSON string.

const student = {
    name: "Ade",
    score: 85
};

const jsonData = JSON.stringify(student);

console.log(jsonData);

Converting JSON to an Object

JSON.parse() converts valid JSON text into a JavaScript value.

const jsonData = '{"name":"Ade","score":85}';

const student = JSON.parse(jsonData);

console.log(student.name);
console.log(student.score);

Common Beginner Mistakes

1. Forgetting Quotes Around String Values

String values should normally be written as strings.

const student = {
    name: "Ade"
};

2. Confusing Dot and Bracket Notation

Use bracket notation when the property name is dynamic.

const property = "name";

console.log(student[property]);

3. Forgetting That Objects Are References

Assigning one object to another does not automatically create an independent copy.

4. Misusing this

The meaning of this depends on how a function is called. Be especially careful when passing methods around as callbacks.

5. Accidentally Modifying Shared Data

When objects are shared between different parts of an application, direct modification can produce unexpected results.

Best Practices for Working with Objects

  • Use meaningful property names.
  • Keep related information together in logical objects.
  • Use consistent object structures when creating collections of records.
  • Use dot notation when the property name is known and valid as an identifier.
  • Use bracket notation for dynamic property access.
  • Use methods when behavior logically belongs to an object.
  • Be careful when modifying objects shared by multiple parts of an application.
  • Use destructuring when it improves readability.
  • Use object spread when creating updated copies is preferable to direct mutation.
  • Keep complex objects organized rather than creating unnecessarily large structures.

Practice Exercise

Create an array containing at least five student objects.

Each student should contain:

  • Name
  • Email
  • Course
  • Score

Your program should:

  1. Display all student names.
  2. Find students who scored at least 50.
  3. Find the student with the highest score.
  4. Calculate the average score.
  5. Display the names of students enrolled in Web Development.
  6. Add a status property to each student.
  7. Create a new object for one student using object spread.
  8. Use destructuring to extract a student’s name and score.
  9. Use Object.keys() to inspect a student object.
  10. Use Object.entries() to display the student’s properties and values.

Lesson Summary

Objects provide a powerful way to organize related information and behavior in JavaScript. They use key-value pairs to represent structured data and can contain strings, numbers, booleans, arrays, nested objects and functions.

You have learned how to create objects, access and modify properties, create methods, use this, work with nested objects, process arrays of objects and use important tools such as Object.keys(), Object.values(), Object.entries(), destructuring and spread syntax.

Objects are fundamental to modern JavaScript because real-world applications constantly work with structured information such as students, users, products, courses, transactions and API responses.

💻

Code Example

const students = [
    {
        name: "Ade",
        email: "ade@example.com",
        course: "Web Development",
        score: 85
    },
    {
        name: "John",
        email: "john@example.com",
        course: "Data Analysis",
        score: 72
    },
    {
        name: "Mary",
        email: "mary@example.com",
        course: "Web Development",
        score: 91
    },
    {
        name: "Grace",
        email: "grace@example.com",
        course: "Cyber Security",
        score: 48
    },
    {
        name: "David",
        email: "david@example.com",
        course: "Web Development",
        score: 67
    }
];

// Display student names
const names = students.map(student => student.name);

console.log("Students:", names);

// Find students who passed
const passedStudents = students.filter(
    student => student.score >= 50
);

console.log("Passed Students:", passedStudents);

// Find the highest-scoring student
const highestStudent = students.reduce(
    (highest, student) =>
        student.score > highest.score ? student : highest
);

console.log("Highest Student:", highestStudent);

// Calculate average score
const totalScore = students.reduce(
    (total, student) => total + student.score,
    0
);

const averageScore = totalScore / students.length;

console.log("Average Score:", averageScore);

// Find Web Development students
const webDevelopmentStudents = students.filter(
    student => student.course === "Web Development"
);

console.log(
    "Web Development Students:",
    webDevelopmentStudents
);

// Object destructuring
const {
    name,
    score
} = students[0];

console.log("Name:", name);
console.log("Score:", score);

// Create an updated copy using spread syntax
const updatedStudent = {
    ...students[0],
    score: 95,
    status: "Active"
};

console.log("Updated Student:", updatedStudent);

// Inspect object properties
console.log("Keys:", Object.keys(updatedStudent));
console.log("Values:", Object.values(updatedStudent));
console.log("Entries:", Object.entries(updatedStudent));
⭐

Key Takeaways

["JavaScript objects store related information using key-value pairs.","Object properties represent data associated with an object.","Dot notation is useful when the property name is known.","Bracket notation is useful for dynamic property access.","Properties can be added, updated and deleted.","Objects can contain arrays and other nested objects.","Functions stored inside objects are commonly called methods.","The this keyword can refer to the object associated with a method call.","Arrays of objects are commonly used to represent application records.","Object.keys() returns an array of property names.","Object.values() returns an array of property values.","Object.entries() returns key-value pairs.","The in operator can check whether a property exists.","Object destructuring makes it easy to extract properties.","Object spread can create updated or combined object copies.","Objects are reference values, so assignments can share the same object.","Spread syntax creates a shallow copy rather than a deep copy.","JavaScript objects are frequently used when processing JSON and API data.","Well-designed objects make applications easier to understand and maintain."]

Enjoying this lesson?

Sign in to your Dwallnet Academy student account to track your learning progress and mark lessons as complete.

Sign In to Track Progress