JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Object Properties


Objects are a fundamental part of JavaScript, allowing you to store and manage data as key-value pairs. Understanding object properties is essential for creating complex applications, managing state, and organizing data efficiently. Object properties provide a way to store information, modify values, and access nested structures, which makes them central to JavaScript programming.

In this tutorial, you will learn about object properties, how to define, access, modify, and delete them, practical examples, common mistakes, best practices, and real-world applications.

Why Object Properties Are Important

Object properties are important because they allow you to:

  • Store structured data in a single entity

  • Organize information logically and efficiently

  • Access, modify, and delete data dynamically

  • Work with complex data structures such as nested objects and arrays

  • Facilitate object-oriented programming in JavaScript

Without understanding object properties, handling dynamic data, building reusable components, or managing application state would be cumbersome and error-prone.

Defining Object Properties

Properties are key-value pairs where the key is a string (or a symbol) and the value can be any valid JavaScript type, including numbers, strings, arrays, functions, or even other objects.

Using Object Literals

const student = {
    name: "Aarushi",
    age: 20,
    course: "JavaScript"
};

Using the Object Constructor

const student = new Object();
student.name = "Isha";
student.age = 22;
student.course = "React";

Both methods create objects with properties that can be accessed and modified.

Accessing Object Properties

You can access properties using dot notation or bracket notation.

Dot Notation

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

Output:

Aarushi
JavaScript

Bracket Notation

Bracket notation is useful when the property name contains spaces or is dynamic:

console.log(student["age"]);
const propertyName = "course";
console.log(student[propertyName]);

Output:

20
JavaScript

Adding and Modifying Properties

Properties can be added or updated at any time:

student.email = "aarushi@example.com";  // Adding a new property
student.age = 21;                        // Modifying an existing property

console.log(student);

Output:

{ name: 'Aarushi', age: 21, course: 'JavaScript', email: 'aarushi@example.com' }

Deleting Properties

You can remove a property using the delete operator:

delete student.course;
console.log(student);

Output:

{ name: 'Aarushi', age: 21, email: 'aarushi@example.com' }

Property Names and Computed Properties

Property names can be strings, symbols, or numbers. You can also use computed property names using square brackets:

const key = "score";
const student = {
    [key]: 95
};
console.log(student.score);

Output:

95

This allows dynamic property names based on variables or expressions.

Nested Objects

Objects can contain other objects as properties, enabling complex data structures:

const student = {
    name: "Priya",
    address: {
        city: "Patna",
        state: "Bihar"
    }
};

console.log(student.address.city);

Output:

Patna

Nested objects are useful for representing real-world entities and hierarchies.

Object Property Methods

Objects can also have methods, which are functions assigned as properties:

const student = {
    name: "Saanvi",
    greet: function() {
        console.log("Hello, my name is " + this.name);
    }
};

student.greet();

Output:

Hello, my name is Saanvi

Methods can access other properties in the same object, enabling encapsulated behavior.

Iterating Over Properties

You can loop through properties using for...in:

for (let key in student) {
    console.log(key + ": " + student[key]);
}

Output:

name: Saanvi
greet: function() { ... }

For only enumerable properties, Object.keys() and Object.values() are useful:

console.log(Object.keys(student));
console.log(Object.values(student));

Output:

[ 'name', 'greet' ]
[ 'Saanvi', [Function: greet] ]

Common Mistakes

  • Accessing properties that do not exist, resulting in undefined

  • Confusing dot notation and bracket notation, especially with dynamic keys

  • Overwriting objects when intending to modify only a property

  • Forgetting to check for nested objects before accessing deep properties

  • Using reserved keywords as property names

Best Practices

  • Use descriptive property names for clarity

  • Use dot notation when possible and bracket notation for dynamic keys

  • Initialize all expected properties to avoid undefined errors

  • Organize nested objects logically to reflect real-world data

  • Avoid unnecessary nested levels for simpler code maintenance

Real-World Applications

  • Storing user profiles and preferences

  • Managing configuration settings

  • Representing hierarchical data, such as menus or organizational charts

  • Maintaining application state in frontend frameworks

  • Encapsulating behavior with object methods

Practical Examples

Example 1: Adding and Updating Properties

const student = { name: "Aarushi", age: 20 };
student.email = "aarushi@example.com";
student.age = 21;

console.log(student);

Example 2: Nested Objects

const student = {
    name: "Priya",
    courses: {
        primary: "JavaScript",
        secondary: "React"
    }
};
console.log(student.courses.secondary);

Example 3: Iterating Properties

const student = { name: "Saanvi", age: 22, course: "Node.js" };
for (let key in student) {
    console.log(key + ": " + student[key]);
}

Example 4: Using Computed Properties

const field = "score";
const student = { [field]: 95 };
console.log(student.score);

Summary of JavaScript Object Properties

JavaScript object properties are the foundation for storing and managing data in key-value pairs. Understanding how to define, access, modify, delete, and iterate over properties is crucial for creating maintainable and efficient applications. Nested objects, computed properties, and object methods enhance the flexibility and power of objects. Proper use of object properties enables developers to manage state, organize data logically, and implement advanced features in real-world applications.


Practice Questions

  1. Create an object car with properties brand, model, and year. Then, log the brand property using dot notation.

  2. Add a new property color to the car object and assign it any value. Log the updated object.

  3. Modify an existing property year in the car object to a new value. Log the updated property.

  4. Delete the property model from the car object. Verify that it has been removed.

  5. Use a property name with space: Create an object employee with a property "job title" and assign a value. Access this property using bracket notation.

  6. Check if a property exists in an object: Use in operator and hasOwnProperty() to check if the property color exists in the car object.

  7. Create a getter property: Create an object student with firstName and lastName. Add a getter property fullName that returns the full name. Log student.fullName.

  8. Create a setter property: Using the student object, add a setter for fullName that splits a string into firstName and lastName. Update the full name using the setter and log both first and last names.

  9. Inspect property attributes: Use Object.getOwnPropertyDescriptor() to check the attributes (writable, enumerable, configurable) of the car object's brand property.

  10. Enumerate all properties of an object: Use for...in and Object.keys() on the student object to list all property names. Compare the output of both methods.


Try a Short Quiz.

No quizzes available.


Online Code Editor and Compilor

Write and run code directly in your browser. Live preview for frontend languages.


JavaScript

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top