const obj ={ key: value };const obj =Object.create(proto);
Example
const user ={
name:"Kai",
age:30,greet(){return`Hi, I'm ${this.name}`;}};console.log(user.greet());
Output
"Hi, I'm Kai"
Note Method shorthand greet() {} is preferred over greet: function() {}. Arrow functions should not be used as methods because they do not bind their own this.
create objectobject literaldefine objectobject with methods
const name ="Mira";const role ="admin";const user ={ name, role };console.log(user);// { name: "Mira", role: "admin" }const field ="email";const form ={[field]:"[email protected]"};console.log(form);// { email: "[email protected]" }
Note Shorthand works when the variable name matches the desired key name. Computed keys are evaluated at runtime.
shorthand propertycomputed property keydynamic keyvariable as key
Object Destructuring in Function Parameters
Syntax
functionfn({ key1, key2 =default}){}
Example
functioncreateUser({ name, role ="viewer", active =true}){return{ name, role, active, createdAt:Date.now()};}const admin =createUser({ name:"Bo", role:"admin"});console.log(admin);
Note Destructuring in parameters makes function signatures self-documenting. Add = {} as a default to allow calling with no arguments: function fn({ x } = {}).
destructure function paramsnamed parametersoptions object pattern
constAPI=Object.freeze({BASE_URL:"https://api.example.com",VERSION:2,});API.VERSION=3;// silently fails (throws in strict mode)console.log(API.VERSION);// 2
Note freeze() prevents all changes. seal() allows modifying existing properties but not adding/removing. Both are shallow -- nested objects remain mutable.