ILILCode
HomeJavaScriptFunctions & data

Objects: grouped, named data

Properties, bracket access, methods, destructuring, spread and the three object static helpers.

Lesson 8 of 23 in JavaScript11 min1 exercise

An object groups named values. Keys are strings (quotes optional when the name is a valid identifier), and a value can be anything — including a function, which then becomes a method.

Creating and reading
const user = {
  name: "Ada",
  role: "engineer",
  city: "London",
};

user.name;        // "Ada"
user["role"];     // "engineer" — bracket access for dynamic keys
const key = "city";
user[key];        // "London"

user.age = 36;    // add a property
delete user.age;  // remove one
Methods and this
const cart = {
  items: ["pen", "notebook"],
  describe() {
    return `${this.items.length} items in the cart`;
  },
};

cart.describe(); // "2 items in the cart"

Destructuring and spread

Pull out what you need
const user = { name: "Ada", role: "engineer", city: "London" };

const { name, city } = user;
const { role: job } = user;              // rename
const { country = "unknown" } = user;    // default

const updated = { ...user, role: "lead" }; // copy + override
const { city: _city, ...rest } = user;      // copy without one key
Listing an object
Object.keys(user);    // ["name", "role", "city"]
Object.values(user);  // ["Ada", "engineer", "London"]
Object.entries(user); // [["name", "Ada"], ["role", "engineer"], ...]

const pairs = Object.entries({ a: 1, b: 2 });
const back = Object.fromEntries(pairs); // { a: 1, b: 2 }

Try it

Copy, rename, list

main.js
console · output appears here

Exercises

Checked in your browser · hints and solutions included

01

Exercise

Pick only the keys you need

Write pick(source, keys) that returns a new object containing only the keys from keys that exist on source. Ignore missing keys and never mutate source.

pick({ a: 1, b: 2 }, ["a"]) → { a: 1 }.

exercise.js
console · run your code or check the answer