Skip to content

Objects

Objects เป็น data structure พื้นฐานที่สุดใน JavaScript — แทบทุกอย่างเป็น object

// สร้าง object
const user = {
name: "สมชาย",
age: 28,
role: "developer",
skills: ["JavaScript", "React", "Node.js"],
};
// เข้าถึง properties
console.log(user.name); // "สมชาย" — dot notation
console.log(user["role"]); // "developer" — bracket notation
// เพิ่ม / แก้ไข property
user.email = "somchai@test.com";
user.age = 29;
const name = "สมหญิง";
const age = 34;
// shorthand — ถ้า key กับ variable ชื่อเดียวกัน
const user = { name, age }; // เท่ากับ { name: name, age: age }
// method shorthand
const calculator = {
add(a, b) { return a + b; },
subtract(a, b) { return a - b; },
};
const product = {
title: "เสื้อยืด",
price: 350,
stock: 100,
category: { main: "เสื้อผ้า", sub: "เสื้อ" },
};
// basic destructuring
const { title, price } = product;
console.log(title); // "เสื้อยืด"
// rename
const { title: productName } = product;
// default value
const { discount = 0 } = product;
// nested destructuring
const { category: { main, sub } } = product;
console.log(main); // "เสื้อผ้า"
// function parameter destructuring
function showProduct({ title, price, stock = 0 }) {
console.log(`${title}: ${price} บาท (เหลือ ${stock})`);
}
showProduct(product);
const defaults = { theme: "dark", lang: "th", fontSize: 16 };
const userPrefs = { lang: "en", fontSize: 18 };
// merge — ค่าที่ซ้ำจะถูก override โดยตัวหลัง
const settings = { ...defaults, ...userPrefs };
// { theme: "dark", lang: "en", fontSize: 18 }
// clone (shallow copy)
const copy = { ...settings };
const field = "email";
const obj = {
[field]: "test@test.com", // { email: "test@test.com" }
[`${field}Verified`]: true, // { emailVerified: true }
};
const user = {
name: "สมชาย",
address: null,
};
// ไม่มี optional chaining — error!
// console.log(user.address.city); // ❌ TypeError
// มี optional chaining — safe
console.log(user.address?.city); // undefined
console.log(user.friends?.[0]?.name); // undefined
console.log(user.greet?.()); // undefined