Objects in JavaScript
Key-value pairs, property access, shorthand syntax, and methods.
2 min read
An object stores data as key-value pairs, where keys are strings (or symbols) and values can be anything — including other objects, arrays, or functions. It's the closest thing JavaScript has to a general-purpose record type.
Creating and accessing objects
const user = {
name: "Ada",
age: 36,
isActive: true,
};
user.name; // "Ada" -- dot notation
user["age"]; // 36 -- bracket notationBracket notation is required when the key is dynamic (stored in a variable) or isn't a valid identifier:
const key = "age";
user[key]; // 36
user["first name"]; // needed -- dot notation can't have a spaceAdding, updating, and deleting properties
user.email = "ada@example.com"; // add
user.age = 37; // update
delete user.isActive; // removeObject methods
A function stored as a property is a method, and can be written with shorthand syntax:
const user = {
name: "Ada",
greet() {
return `Hi, I'm ${this.name}`;
},
};
user.greet(); // "Hi, I'm Ada"Shorthand property names
When a variable's name matches the key you want, you can skip repeating it:
const name = "Ada";
const age = 36;
const user = { name, age }; // same as { name: name, age: age }Checking for a property
"name" in user; // true -- checks own and inherited properties
user.hasOwnProperty("name"); // true -- checks only own properties
user.missing !== undefined; // works, but breaks if the value is legitimately undefinedin and hasOwnProperty are the reliable checks; comparing against undefined directly can give a false negative if a property exists but was explicitly set to undefined.
Getting keys, values, and entries
Object.keys(user); // ["name", "age", "greet"]
Object.values(user); // ["Ada", 36, function]
Object.entries(user); // [["name", "Ada"], ["age", 36], ...]Object.entries() combined with a for...of loop is the standard way to iterate over both keys and values together.
Objects and arrays are the two data structures nearly every JavaScript program is built on top of. The next lesson covers destructuring — a syntax for pulling values out of both in one step.