← Back to Chapters

JavaScript Objects: Properties, Methods, Display, Constructors

? JavaScript Objects: Properties, Methods, Display, Constructors

⚡ Quick Overview

JavaScript objects let you group related data and behavior together. Properties store data about the object, methods define what the object can do, and constructors/classes help you create many similar objects easily.

? Properties = Data   ⚙️ Methods = Actions   ?️ Constructors = Object Factory

? Key Concepts

  • Object properties are key–value pairs that describe the object.
  • Methods are functions stored as properties that operate on the object’s data.
  • this refers to the current object inside a method or constructor.
  • Displaying objects can be done via loops or converting them to JSON strings.
  • Constructors/functions & classes are used to create multiple similar objects.

? Syntax and Theory

? Object Properties

An object literal is written with curly braces {}. Each property is a key: value pair. You can access properties using dot notation (obj.key) or bracket notation (obj["key"]).

⚙️ Methods and this

When a function is stored as a property, it is called a method. Inside methods, this points to the object that owns the method (when called as obj.method()).

? Displaying Object Data

You can loop over properties using for...in or convert the entire object into a JSON string using JSON.stringify() for easy logging or sending over a network.

?️ Constructors and Classes

Constructor functions (pre-ES6) and class syntax (ES6+) provide patterns to create many objects with the same structure. Use the new keyword to create instances.

? Code Examples

? View Object Properties Example
// Defining an object with properties
const car = {
  make: "Toyota",
  model: "Corolla",
  year: 2020
};

// Accessing properties
console.log(car.make);        // Output: Toyota
console.log(car["model"]);    // Output: Corolla

// Adding or modifying properties
car.color = "Blue";
car.year = 2021;

console.log(car.color);       // Output: Blue
console.log(car.year);        // Output: 2021
? View Methods Example
const person = {
  firstName: "Jane",
  lastName: "Doe",
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

console.log(person.fullName()); // Output: Jane Doe

// ES6 shorthand for methods
const person2 = {
  firstName: "John",
  lastName: "Smith",
  fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
};

console.log(person2.fullName()); // Output: John Smith
? View Display and JSON Example
// Loop through properties using for...in
for (let key in car) {
  console.log(key + ": " + car[key]);
}
/*
Output:
make: Toyota
model: Corolla
year: 2021
color: Blue
*/

// Convert object to JSON string
const jsonStr = JSON.stringify(car);
console.log(jsonStr);
// Example output:
// {"make":"Toyota","model":"Corolla","year":2021,"color":"Blue"}

// Parse JSON string back to object
const newCar = JSON.parse(jsonStr);
console.log(newCar.make); // Output: Toyota
?️ View Constructor Function Example
// Constructor function example
function Animal(type, sound) {
  this.type = type;
  this.sound = sound;
  this.speak = function() {
    return `${this.type} says ${this.sound}`;
  };
}

// Create new instances
const dog = new Animal("Dog", "Woof");
const cat = new Animal("Cat", "Meow");

console.log(dog.speak()); // Output: Dog says Woof
console.log(cat.speak()); // Output: Cat says Meow
? View Class Syntax Example
// ES6 Class syntax (modern way)
class AnimalClass {
  constructor(type, sound) {
    this.type = type;
    this.sound = sound;
  }

  speak() {
    return `${this.type} says ${this.sound}`;
  }
}

const bird = new AnimalClass("Bird", "Chirp");
console.log(bird.speak()); // Output: Bird says Chirp

? Live Output and Explanation

? What the Code Is Doing

  • The car object stores details like make, model, year, and color. You can read and update these using dot or bracket notation.
  • The person and person2 objects both define a fullName() method that uses this.firstName and this.lastName.
  • The for...in loop prints every property name and value of car.
  • JSON.stringify(car) turns the object into a string for logging or sending over a network, and JSON.parse() reverses it back into an object.
  • The constructor Animal and class AnimalClass both define a pattern for creating objects with type, sound, and a speak() method.

? Use Cases and When to Use

  • Representing real-world entities like cars, users, products, and orders.
  • Grouping related configuration or settings in a single object.
  • Building reusable models with constructors or classes (e.g., User, Post).
  • Sending and receiving structured data in JSON format between client and server.

? Interactive Example

Click the button to display information from a JavaScript object:

? Result

Click the button to see the car details here.

? Tips and Best Practices

  • Use methods to keep functionality close to the data it works on.
  • Prefer constructor functions or classes when you need many similar objects.
  • Use for...in carefully; it iterates over all enumerable properties, including inherited ones.
  • Always use the new keyword with constructor functions to ensure this refers to the new object.
  • Avoid using arrow functions for object methods that rely on this, since arrow functions do not have their own this.

? Try It Yourself

  • Create an object book with properties: title, author, and pages.
  • Add a method that returns a formatted string about the book (e.g., "Title by Author (X pages)").
  • Use a for...in loop to print all properties and values of the book object.
  • Create a constructor function or class to create multiple book objects.
  • Extend your class with a method like isLongBook() that returns true if pages > 300.