#CodeNewbie

#CodingTips

#Frontend

#Fullstack

#JavaScript

#LearnToCode

#Programming

#WebDevelopment

Objects in JavaScript: creating, accessing keys and nested structures

 

Objects are the backbone of JavaScript. Almost everything in JS is an object — arrays, functions, dates, and more. Understanding how to create, access, modify, and nest objects is one of the most important fundamentals you can master. This article covers everything you need to know.


 

What is an object?

An object is a collection of key-value pairs. The keys are strings (or symbols), and the values can be anything — strings, numbers, booleans, arrays, functions, or even other objects. Objects let you group related data and behaviour together in one place.

const person = {
  name: "Alice",
  age: 30,
  isActive: true
};

// key: "name" → value: "Alice"
// key: "age" → value: 30

 

Creating objects

1. Object literal (most common)

const car = {
  brand: "Toyota",
  model: "Camry",
  year: 2024,
  isElectric: false
};

2. Object constructor

const obj = new Object();
obj.name = "Alice";
obj.age = 30;
// Less common — prefer object literals

3. Object.create()

const proto = { greet() { return "Hello!"; } };
const obj2 = Object.create(proto);
obj2.name = "Bob";
obj2.greet();  →  "Hello!"  ← inherited from proto

 

Accessing properties

There are two ways to access a property: dot notation and bracket notation. Both work, but they are useful in different situations.

Dot notation

const person = { name: "Alice", age: 30 };

person.name   →  "Alice"
person.age    →  30
person.email  →  undefined  ← missing key, no error

Bracket notation

person["name"]           →  "Alice"

// Useful when key is a variable:
const key = "age";
person[key]              →  30

// Useful for keys with spaces or special chars:
const obj = { "first name": "Alice" };
obj["first name"]        →  "Alice"
obj.first name           →  SyntaxError!
Rule of thumb: use dot notation by default. Switch to bracket notation when the key is stored in a variable, contains spaces, or is dynamic.

 

Adding, updating and deleting properties

const user = { name: "Alice" };

// Add a new property
user.age = 30;
user["email"] = "[email protected]";

// Update an existing property
user.name = "Bob";

// Delete a property
delete user.email;

console.log(user);  →  { name: "Bob", age: 30 }

 

Methods — functions inside objects

A method is simply a function stored as a property of an object. Inside a method, the this keyword refers to the object itself.

const person = {
  name: "Alice",
  age: 30,
  greet() {
    return `Hi, I'm ${this.name} and I'm ${this.age}.`;
  }
};

person.greet();  →  "Hi, I'm Alice and I'm 30."

 

Nested objects

Objects can contain other objects, arrays, or any combination. This is how real-world data is usually structured.

const user = {
  name: "Alice",
  address: {
    city: "Hanoi",
    country: "Vietnam"
  },
  hobbies: ["coding", "reading", "travel"]
};

// Accessing nested properties
user.address.city       →  "Hanoi"
user.address.country    →  "Vietnam"
user.hobbies[0]         →  "coding"
user.hobbies.length     →  3

 

Looping through objects

for...in loop

const scores = { Alice: 95, Bob: 87, Carol: 92 };

for (const key in scores) {
  console.log(`${key}: ${scores[key]}`);
}
→  Alice: 95
→  Bob: 87
→  Carol: 92

Object.keys(), Object.values(), Object.entries()

const person = { name: "Alice", age: 30, city: "Hanoi" };

Object.keys(person)    →  ["name", "age", "city"]
Object.values(person)  →  ["Alice", 30, "Hanoi"]
Object.entries(person) →  [["name","Alice"], ["age",30], ["city","Hanoi"]]

// Practical: loop with entries
Object.entries(person).forEach(([key, value]) => {
  console.log(`${key}: ${value}`);
});

 

Copying objects

Objects are passed by reference in JavaScript — assigning an object to a new variable does not copy it, it creates another reference to the same object.

// Reference — NOT a copy
const a = { name: "Alice" };
const b = a;
b.name = "Bob";
console.log(a.name);  →  "Bob"  ← a was changed too!

// Shallow copy using spread
const c = { ...a };
c.name = "Carol";
console.log(a.name);  →  "Bob"  ← a is safe now

// Shallow copy using Object.assign()
const d = Object.assign({}, a);

// Deep copy (for nested objects)
const e = JSON.parse(JSON.stringify(a));
Spread only does a shallow copy. If your object has nested objects, the nested parts are still shared by reference. Use JSON.parse(JSON.stringify(obj)) for a simple deep copy, or use a library like structuredClone() (modern browsers) for more complex cases.

 

Useful Object utility methods

// Check if key exists
"name" in person            →  true
person.hasOwnProperty("age") →  true

// Merge two objects
const defaults = { theme: "light", lang: "en" };
const settings = { lang: "vi", fontSize: 14 };
const merged = { ...defaults, ...settings };
→  { theme: "light", lang: "vi", fontSize: 14 }
// settings overrides defaults for duplicate keys

// Freeze an object — prevent modifications
const config = Object.freeze({ apiUrl: "https://api.example.com" });
config.apiUrl = "hacked";  ← silently ignored

 

Key takeaways

Objects are collections of key-value pairs — the most fundamental data structure in JavaScript. Use dot notation for clean, readable access and bracket notation when keys are dynamic or contain special characters. Objects can be nested to represent complex real-world data. Always remember that objects are passed by reference — use spread or Object.assign() to create a shallow copy and prevent accidental mutations. Use Object.keys(), Object.values(), and Object.entries() to loop through an object cleanly.