In JavaScript, an object is a composite data type made of properties and methods. Properties are key-value pairs, and methods are properties whose values are functions.

Almost everything in JavaScript is either an object or can be treated like one.

1. Creating Objects

a. Object literal

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

b. new Object()

const user = new Object();
user.name = "Tom";
user.age = 20;

In practice, object literals are usually preferred.

2. Properties

a. Accessing properties

const user = { name: "Tom", age: 20 };
console.log(user.name);
console.log(user["age"]);

Dot notation is simpler. Bracket notation is useful when the property name is dynamic.

b. Updating and adding properties

user.age = 21;
user.city = "Tokyo";

c. Deleting properties

delete user.city;

d. Computed property names

const key = "score";
const result = {
[key]: 100,
};

e. Checking whether a property exists

"name" in user; // true
user.hasOwnProperty("age"); // true

f. Property value shorthand

const name = "Tom";
const age = 20;
const user = { name, age };

3. Methods

Objects can contain methods:

const user = {
name: "Tom",
sayHello() {
console.log(`Hello, I am ${this.name}`);
},
};

The this keyword

Inside an object method, this usually refers to the object used to call the method.

user.sayHello();

Understanding this is one of the key parts of understanding JavaScript objects.

4. Prototype and Prototype Chain

a. Core idea

JavaScript uses prototypes as a core inheritance mechanism.

If a property does not exist on the object itself, JavaScript looks for it on the prototype.

b. Practical example

const animal = {
eat() {
console.log("eating");
},
};
const dog = Object.create(animal);
dog.bark = function () {
console.log("woof");
};
dog.eat(); // inherited from animal
dog.bark();

c. Prototype chain

Property lookup follows the prototype chain upward until:

  • the property is found
  • or the chain ends with null

d. constructor

Functions used as constructors expose a prototype object, and instances usually have access to a constructor reference through that prototype.

function User(name) {
this.name = name;
}
const user = new User("Tom");
console.log(user.constructor === User); // true

Summary

Objects are central to JavaScript. To use them well, you should understand:

  • how to create them
  • how property access works
  • how methods and this behave
  • how prototypes and the prototype chain work