🔍 Object Definitions in JavaScript

In JavaScript, an object is a non-primitive data type that allows you to store multiple values in a single variable. These values are stored as key-value pairs, where keys are also called properties.

✅ Basic Definition

An object in JavaScript is defined using curly braces {}, with properties inside.

🧱 Syntax:

javascriptCopyEditconst objectName = {
  key1: value1,
  key2: value2,
  key3: value3
};

🧪 Example:

javascriptCopyEditconst person = {
  name: "Alice",
  age: 30,
  isStudent: false
};

In this example:

  • "name" is a property with the value "Alice" (a string).
  • "age" is a property with the value 30 (a number).
  • "isStudent" is a property with the value false (a boolean).

🧰 Ways to Define Objects

1. Object Literal (Most Common)

javascriptCopyEditconst car = {
  brand: "Toyota",
  year: 2022
};

2. Using the new Object() Constructor

javascriptCopyEditconst car = new Object();
car.brand = "Toyota";
car.year = 2022;

3. Using a Constructor Function

javascriptCopyEditfunction Person(name, age) {
  this.name = name;
  this.age = age;
}

const user1 = new Person("Bob", 25);

4. Using ES6 Classes

javascriptCopyEditclass Animal {
  constructor(name, species) {
    this.name = name;
    this.species = species;
  }
}

const dog = new Animal("Buddy", "Dog");

🔁 Accessing Object Properties

Dot Notation:

javascriptCopyEditconsole.log(person.name); // "Alice"

Bracket Notation (useful for dynamic keys):

javascriptCopyEditconst key = "age";
console.log(person[key]); // 30

✏️ Summary: What is an Object in JS?

FeatureDescription
TypeNon-primitive
StructureKey-value pairs
Definition MethodsLiteral, Constructor, Class
Access MethodsDot . or Bracket [] notation