Objects
Objects
Section titled “Objects”Objects เป็น data structure พื้นฐานที่สุดใน JavaScript — แทบทุกอย่างเป็น object
Object Literals
Section titled “Object Literals”// สร้าง objectconst user = { name: "สมชาย", age: 28, role: "developer", skills: ["JavaScript", "React", "Node.js"],};
// เข้าถึง propertiesconsole.log(user.name); // "สมชาย" — dot notationconsole.log(user["role"]); // "developer" — bracket notation
// เพิ่ม / แก้ไข propertyuser.email = "somchai@test.com";user.age = 29;user = { "name": "สมชาย", "age": 28, "role": "developer",}print(user["name"])// C ใช้ structstruct User { char name[50]; int age; char role[20]; };struct User user = {"สมชาย", 28, "developer"};-- SQL เก็บเป็น row ใน tableSELECT name, age, role FROM users WHERE id = 1;Shorthand Properties & Methods
Section titled “Shorthand Properties & Methods”const name = "สมหญิง";const age = 34;
// shorthand — ถ้า key กับ variable ชื่อเดียวกันconst user = { name, age }; // เท่ากับ { name: name, age: age }
// method shorthandconst calculator = { add(a, b) { return a + b; }, subtract(a, b) { return a - b; },};Destructuring
Section titled “Destructuring”const product = { title: "เสื้อยืด", price: 350, stock: 100, category: { main: "เสื้อผ้า", sub: "เสื้อ" },};
// basic destructuringconst { title, price } = product;console.log(title); // "เสื้อยืด"
// renameconst { title: productName } = product;
// default valueconst { discount = 0 } = product;
// nested destructuringconst { category: { main, sub } } = product;console.log(main); // "เสื้อผ้า"
// function parameter destructuringfunction showProduct({ title, price, stock = 0 }) { console.log(`${title}: ${price} บาท (เหลือ ${stock})`);}showProduct(product);Spread & Merge
Section titled “Spread & Merge”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 };Computed Property Names
Section titled “Computed Property Names”const field = "email";const obj = { [field]: "test@test.com", // { email: "test@test.com" } [`${field}Verified`]: true, // { emailVerified: true }};Optional Chaining (?.)
Section titled “Optional Chaining (?.)”const user = { name: "สมชาย", address: null,};
// ไม่มี optional chaining — error!// console.log(user.address.city); // ❌ TypeError
// มี optional chaining — safeconsole.log(user.address?.city); // undefinedconsole.log(user.friends?.[0]?.name); // undefinedconsole.log(user.greet?.()); // undefined