Appearance
Objects
JavaScript objects are collections of key-value pairs where values can be data or functions. They provide a way to group related data and behaviour together. Here, we introduce how to create objects directly, but we'll also see another way using the class syntax in a later section.
Create an Object
The simplest way to create an object is using object literal syntax. While it uses curly brackets like code blocks, here they define an object:
js
// Empty object
const empty = {};
// Object with keys and values
const user = {
name: "Sam",
age: 20,
isAdmin: true,
sayHi() {
return "Hello!";
}
};
// You can also write it on one line if the object is small
const point = { x: 10, y: 20 };Each property is written as a key followed by a colon and a value. The last property may have a trailing comma.
Properties
Object properties are key-value pairs, thought the "key" is often referred to as the "name" of the property. Property keys (or "names") can be:
- Valid identifiers (letters, numbers, _, $, cannot start with a number if not all digits)
- Numbers (they become strings)
- Any string if you use quotes (needed for spaces or special characters)
js
const item = {
name: "Widget", // Simple identifier
"serial number": "A123", // String with space needs quotes
"price-tag": 42.99, // Hyphens need quotes
1: "first", // Number becomes string "1"
};You can access properties in two ways:
js
// Dot notation (for simple identifiers)
console.log(item.name); // "Widget"
// Bracket notation (works with any string)
console.log(item["serial number"]); // "A123"👉 In general, you should use camelCase (first character lowercase) for property names.
Methods
Objects can include functions as properties, which we usually refer to as methods:
js
const greeter = {
message: "Hello",
// Simple method that doesn't need object properties
sayHi() {
return "Hi!";
},
// Method using 'this' to access object properties
greet() {
return this.message + "!";
}
};
console.log(greeter.sayHi()); // "Hi!"
console.log(greeter.greet()); // "Hello!"The keyword this inside a method refers to the object itself, letting you access its properties. This is particularly useful when properties might change:
js
greeter.message = "Bonjour";
console.log(greeter.greet()); // "Bonjour!"Modifying Objects
Objects are mutable, you can change their properties (and even change methods) after creation:
js
const circle = {
radius: 5,
colour: "blue"
};
// Change existing properties
circle.colour = "green";
// Add new properties
circle.name = "My Circle";
// Delete properties
delete circle.name;Object variables are references to the object in memory. When using const, only this reference is immutable, meaning you can't make the variable point to a different object. The object's properties can still be modified through this reference:
js
const user = { name: "Sam" };
user.name = "Alex"; // OK: modifying through the reference
// user = { name: "Alex" }; // Error: can't change the referenceOptional Chaining
The ?. operator safely accesses nested properties without crashing if any part is undefined.
For example, when accessing properties of a variable that might be undefined:
js
const user;
console.log(user?.name); // undefined (no error)
console.log(user.name); // TypeErrorYou can also use optional chaining to safely access nested object properties:
js
const user1 = { name: "Alice", address: { street: "Main St" } };
const user2 = { name: "Bob" }; // Missing address
console.log(user1.address?.street); // "Main St"
console.log(user2.address?.street); // undefined (no error)Common Uses
Objects are often used to:
Group Related Values
Instead of managing multiple separate variables:
js
const playerX = 100;
const playerY = 200;
const playerHealth = 100;
const playerName = "Hero";
// Hard to pass around, easy to forget a value
updatePlayer(playerX, playerY, playerHealth, playerName);Group them in an object:
js
const player = {
x: 100,
y: 200,
health: 100,
name: "Hero"
};
// Easier to pass around, clearer what the values mean
updatePlayer(player);Configure Function Behaviour
Instead of having many optional parameters:
js
// Hard to remember parameter order
drawBox(100, 200, "red", 2, true, false, "round");Use an options object:
js
drawBox({
width: 100,
height: 200,
colour: "red",
borderWidth: 2,
filled: true,
shadow: false,
corners: "round"
});External Resources