Objects & Classes
Prerequisites:
Objects are collections of key-value pairs. They’re fundamental to JavaScript programming.
Creating Objects
Section titled “Creating Objects”// Object literalconst user = { name: "Alice", age: 30, isAdmin: false};
// Object constructorconst obj = new Object();obj.name = "Bob";
// Object.create()const proto = { greet() { return "Hello!"; } };const child = Object.create(proto);Accessing Properties
Section titled “Accessing Properties”const user = { name: "Alice", age: 30 };
// Dot notationuser.name; // "Alice"
// Bracket notationuser["age"]; // 30
// Dynamic keysconst key = "name";user[key]; // "Alice"
// Optional chaininguser.address?.city; // undefined (no error)Modifying Objects
Section titled “Modifying Objects”const user = { name: "Alice" };
// Add/update propertiesuser.age = 30;user["email"] = "alice@example.com";
// Delete propertiesdelete user.email;
// Prevent modificationsObject.freeze(user); // Can't add, delete, or modifyObject.seal(user); // Can't add or delete, but can modifyObject.preventExtensions(user); // Can't add new propertiesObject Methods
Section titled “Object Methods”const user = { name: "Alice", age: 30 };
// Get keys, values, entriesObject.keys(user); // ["name", "age"]Object.values(user); // ["Alice", 30]Object.entries(user); // [["name", "Alice"], ["age", 30]]
// Merge objectsconst defaults = { theme: "dark", lang: "en" };const settings = { theme: "light" };const merged = { ...defaults, ...settings };// { theme: "light", lang: "en" }
// Or with Object.assignObject.assign({}, defaults, settings);
// Check properties"name" in user; // trueuser.hasOwnProperty("name"); // trueObject.hasOwn(user, "name"); // true (ES2022)Destructuring
Section titled “Destructuring”const user = { name: "Alice", age: 30, address: { city: "NYC", zip: "10001" }};
// Basic destructuringconst { name, age } = user;
// Rename variablesconst { name: userName } = user;
// Default valuesconst { role = "user" } = user;
// Nested destructuringconst { address: { city } } = user;
// Rest operatorconst { name, ...rest } = user;// rest = { age: 30, address: {...} }Shorthand Syntax
Section titled “Shorthand Syntax”const name = "Alice";const age = 30;
// Property shorthandconst user = { name, age };// Same as: { name: name, age: age }
// Method shorthandconst obj = { greet() { return "Hello!"; }};// Same as: greet: function() {...}
// Computed property namesconst key = "dynamic";const obj2 = { [key]: "value", [`${key}Method`]() { return "Hi"; }};Classes (ES6)
Section titled “Classes (ES6)”class User { // Private field (ES2022) #password;
// Constructor constructor(name, email) { this.name = name; this.email = email; this.#password = ""; }
// Instance method greet() { return `Hello, I'm ${this.name}`; }
// Getter get displayName() { return this.name.toUpperCase(); }
// Setter set password(value) { if (value.length >= 8) { this.#password = value; } }
// Static method static createGuest() { return new User("Guest", "guest@example.com"); }}
const alice = new User("Alice", "alice@example.com");alice.greet(); // "Hello, I'm Alice"alice.displayName; // "ALICE"User.createGuest(); // User { name: "Guest", ... }Inheritance
Section titled “Inheritance”class Animal { constructor(name) { this.name = name; }
speak() { return `${this.name} makes a sound`; }}
class Dog extends Animal { constructor(name, breed) { super(name); // Call parent constructor this.breed = breed; }
speak() { return `${this.name} barks!`; }
fetch() { return `${this.name} fetches the ball`; }}
const dog = new Dog("Rex", "German Shepherd");dog.speak(); // "Rex barks!"dog.fetch(); // "Rex fetches the ball"Next Steps
Section titled “Next Steps”Ready for advanced topics? Learn about Async JavaScript to handle asynchronous operations.