JS Basics
JavaScript Objects
Work with JavaScript objects, methods, property shorthand, destructuring, and spread syntax.
JavaScript Objects
Objects are used to store collections of data and more complex entities. An object can be created with figure brackets {…} with an optional list of properties.
A property is a "key: value" pair, where key is a string (also called a "property name"), and value can be anything.
Accessing Properties
You can access object properties with dot notation or bracket notation.
Object Methods
Methods are functions stored as object properties.
Object Destructuring
Destructuring lets you unpack properties from objects into variables.
Example
javascript
// Creating objects
const user = {
name: "Alice",
age: 28,
role: "developer",
skills: ["JavaScript", "Python", "React"],
address: {
city: "San Francisco",
country: "USA"
}
};
// Accessing properties
console.log(user.name); // Alice
console.log(user["age"]); // 28
console.log(user.address.city); // San Francisco
// Object methods
const calculator = {
value: 0,
add(n) { this.value += n; return this; },
subtract(n) { this.value -= n; return this; },
result() { return this.value; }
};
console.log(calculator.add(10).subtract(3).result()); // 7
// Destructuring
const { name, age, role = "user" } = user;
const { city, country } = user.address;
// Property shorthand
const x = 10, y = 20;
const point = { x, y }; // { x: 10, y: 20 }
// Spread
const admin = { ...user, role: "admin", verified: true };
// Object.keys / values / entries
console.log(Object.keys(user));
console.log(Object.values(user));
Object.entries(user).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});Try it yourself — JAVASCRIPT