JavaScript Object Definitions

Learn how to create and define objects in JavaScript

📦 What are JavaScript Objects?

Objects are containers for named values called properties and methods. They are one of the most important data types in JavaScript.


// Simple object example
let person = {
    name: "John",
    age: 30,
    city: "New York"
};
                                    

Ways to Create Objects

🏗️

Object Literal

The simplest way to create objects

let car = {
    brand: "Toyota",
    model: "Camry"
};
🔧

new Object()

Using the Object constructor

let car = new Object();
car.brand = "Toyota";
car.model = "Camry";
🏭

Constructor Function

Create multiple similar objects

function Car(brand, model) {
    this.brand = brand;
    this.model = model;
}

Object.create()

Create objects with specific prototype

let car = Object.create(null);
car.brand = "Toyota";

🔹 Object Literal Syntax

The most common way to create objects using curly braces:

// Basic object literal
let student = {
    firstName: "Alice",
    lastName: "Johnson",
    age: 20,
    grade: "A",
    isActive: true
};

console.log(student.firstName); // "Alice"
console.log(student.age);       // 20

Console Output:

Alice

20

🔹 Empty Objects

You can create empty objects and add properties later:

// Create empty object
let book = {};

// Add properties
book.title = "JavaScript Guide";
book.author = "John Doe";
book.pages = 300;

console.log(book);
// Output: {title: "JavaScript Guide", author: "John Doe", pages: 300}

Console Output:

{title: "JavaScript Guide", author: "John Doe", pages: 300}

🔹 Nested Objects

Objects can contain other objects as properties:

let employee = {
    name: "Sarah",
    position: "Developer",
    address: {
        street: "123 Main St",
        city: "Boston",
        zipCode: "02101"
    },
    skills: ["JavaScript", "HTML", "CSS"]
};

console.log(employee.name);           // "Sarah"
console.log(employee.address.city);   // "Boston"
console.log(employee.skills[0]);      // "JavaScript"

Console Output:

Sarah

Boston

JavaScript

🔹 Object with Methods

Objects can contain functions as properties (called methods):

let calculator = {
    x: 10,
    y: 5,
    add: function() {
        return this.x + this.y;
    },
    multiply: function() {
        return this.x * this.y;
    }
};

console.log(calculator.add());      // 15
console.log(calculator.multiply()); // 50

Console Output:

15

50

🧠 Test Your Knowledge

Which is the correct way to create an object literal?