What is an object in JavaScript?
Object in JavaScript
In JavaScript, an object is one of the fundamental data structures that allows storing values in key:value format.
Let's say you want to describe a person's data: the best option for this is an object.
const person = { firstName: "Aram", lastName: "Khachatryan", age: 30, isDeveloper: true };
This code creates an object named person that stores information about a person.
There are two ways:
console.log(person.firstName); // Aram
console.log(person["lastName"]); // Khachatryan
Bracket notation is useful when the property name is stored in a variable:
const key = "age"; console.log(person[key]); // 30
person.age = 31; // modifies existing value person.city = "Yerevan"; // adds new property
We can also add functions to objects, which we call methods.
const person = { firstName: "Aram", lastName: "Khachatryan", fullName() { return this.firstName + " " + this.lastName; } }; console.log(person.fullName()); // Aram Khachatryan
const keys = Object.keys(person); // ['firstName', 'lastName'] const values = Object.values(person); // ['Aram', 'Khachatryan'] const entries = Object.entries(person); // [['firstName', 'Aram'], ['lastName', 'Khachatryan']]
const a = { x: 1 }; const b = { x: 1 }; console.log(a === b); // false
Objects are compared by reference, not by content.
In JavaScript, when you simply assign an object from one variable to another, you're actually copying the reference, not the object itself.
const original = { name: "Aram" }; const copy = original; copy.name = "Mariam"; console.log(original.name); // Mariam
This way, both variables reference the same object.
const original = { name: "Aram" }; const copy = Object.assign({}, original); copy.name = "Mariam"; console.log(original.name); // Aram
const copy = { ...original };
When an object contains another object:
const user = { name: "Aram", contact: { email: "aram@example.com", phone: "099123456" } };
Accessing:
console.log(user.contact.email); // aram@example.com
Object.assign or { ...obj } don't perform deep cloning of nested objects.
const clone = { ...user }; clone.contact.email = "mariam@example.com"; console.log(user.contact.email); // mariam@example.com
Here, while the top level is cloned, contact still references the same object.
Simplest method: JSON hack (works only if object doesn't contain functions)
const deepClone = JSON.parse(JSON.stringify(user));
Or use libraries like lodash's cloneDeep.
Feature | Object.assign | Spread Operator |
Syntax | Long | Short |
Deep Clone | ❌ | ❌ |
Merge Multiple | ✅ | ✅ |
const a = { x: 1 }; const b = { y: 2 }; const merged1 = Object.assign({}, a, b); const merged2 = { ...a, ...b };