🏠 Home / Hub

⚡ JavaScript Lesson 06 — Objects

← Back to JS Menu

1. Object Literals

// Object = key: value pairs
const person = {
  name: "Ko Min",
  age: 25,
  city: "Yangon",
  isStudent: false
}

// Access values
person.name         // "Ko Min" — dot notation
person["age"]       // 25 — bracket notation (for dynamic keys)

// Modify
person.age = 26
person["city"] = "Mandalay"

// Add new property
person.email = "min@email.com"

// Delete property
delete person.isStudent

// Check property exists
"name" in person          // true
person.hasOwnProperty("age") // true

2. Object Methods (Functions inside Objects)

const person = {
  name: "Ko Min",
  age: 25,
  greet() {                      // method shorthand
    return `Hello, I'm ${this.name}`   // this = object itself
  },
  getBirthYear() {
    return new Date().getFullYear() - this.age
  }
}

person.greet()         // "Hello, I'm Ko Min"
person.getBirthYear()  // e.g. 1999

3. Destructuring

const person = { name: "Ko Min", age: 25, city: "Yangon" }

// Object destructuring
const { name, age } = person
console.log(name)  // "Ko Min"
console.log(age)   // 25

// Rename while destructuring
const { name: fullName, city: location } = person
console.log(fullName)  // "Ko Min"
console.log(location)  // "Yangon"

// Default values
const { email = "none", name: nm } = person
console.log(email)  // "none" (not in object)

// In function parameters
function display({ name, age }) {
  return `${name} is ${age}`
}
display(person)  // "Ko Min is 25"

4. Spread Operator & Object.assign

const base = { name: "Min", age: 25 }
const extra = { city: "Yangon", job: "Dev" }

// Spread — combine objects
const merged = { ...base, ...extra }
// { name:"Min", age:25, city:"Yangon", job:"Dev" }

// Copy object (shallow)
const copy = { ...base }

// Override property
const updated = { ...base, age: 30 }
// { name:"Min", age:30 }

// Object.assign (old way)
const result = Object.assign({}, base, extra)

5. Object.keys / values / entries

const car = { brand: "Toyota", model: "Camry", year: 2023, price: 30000 }

Object.keys(car)
// ["brand", "model", "year", "price"]

Object.values(car)
// ["Toyota", "Camry", 2023, 30000]

Object.entries(car)
// [["brand","Toyota"], ["model","Camry"], ...]

// Loop through object
Object.entries(car).forEach(([key, value]) => {
  console.log(`${key}: ${value}`)
})

6. JSON — JavaScript Object Notation

// Object → JSON string (for API/storage)
const person = { name: "Min", age: 25, hobbies: ["code", "music"] }
const jsonStr = JSON.stringify(person)
// '{"name":"Min","age":25,"hobbies":["code","music"]}'

// Pretty print
JSON.stringify(person, null, 2)
// {
//   "name": "Min",
//   "age": 25,
//   "hobbies": ["code", "music"]
// }

// JSON string → Object
const parsed = JSON.parse(jsonStr)
parsed.name  // "Min"

// localStorage save/load
localStorage.setItem("user", JSON.stringify(person))
const user = JSON.parse(localStorage.getItem("user"))

7. Nested Objects & Optional Chaining

const user = {
  name: "Ko Min",
  address: {
    street: "123 Main St",
    city: {
      name: "Yangon",
      zip: "11001"
    }
  },
  scores: [95, 87, 92]
}

// Access nested
user.address.city.name         // "Yangon"
user.scores[0]                 // 95

// Optional chaining ?. — avoid error if undefined
const country = user.address?.country?.name  // undefined (no error!)
user.phone?.number             // undefined (no error!)

// Nullish coalescing with ?.
const zip = user.address?.city?.zip ?? "No zip"  // "11001"

← JS 05  |  Next: JS Lesson 07 → DOM →

📌 Study Checklist