JavaScript Tutorial · Objects and Arrays · Lesson 22 of 44

JavaScript Objects

Create objects, read and update properties, and add methods.

Object literals

An object groups related values as key: value pairs (properties):

Example 1Try it yourself
const user = {
  name: "Ada",
  age: 36,
  "favourite-language": "JavaScript",
};
console.log(user.name);
console.log(user["favourite-language"]);
user.age = 37;          // update
user.email = "[email protected]"; // add
delete user["favourite-language"];
console.log(user);
console.log("email" in user, user.phone);

Output

Ada
JavaScript
{ name: 'Ada', age: 37, email: '[email protected]' }
true undefined

Use dot notation (user.name) normally, and bracket notation (user["first-name"] or user[key]) when the key is dynamic or not a valid identifier.

Methods

A function stored in an object is a method. Inside it, this refers to the object it was called on:

Example 2Try it yourself
const account = {
  owner: "Ada",
  balance: 100,
  deposit(amount) {
    this.balance += amount;
    return this.balance;
  },
};
account.deposit(50);
console.log(`${account.owner} has $${account.balance}`);

Output

Ada has $150

Shorthand and computed keys

Example 3Try it yourself
const name = "Ada";
const role = "admin";
const field = "lastLogin";
const user = { name, role, [field]: "2026-10-01" };
console.log(user);

Output

{ name: 'Ada', role: 'admin', lastLogin: '2026-10-01' }

Useful Object helpers

Object.keys(), Object.values() and Object.entries() turn an object into arrays; Object.fromEntries() goes back:

Example 4Try it yourself
const stock = { apples: 5, pears: 0, plums: 12 };
console.log(Object.keys(stock));
console.log(Object.values(stock));
const inStock = Object.fromEntries(Object.entries(stock).filter(([, qty]) => qty > 0));
console.log(inStock);

Output

[ 'apples', 'pears', 'plums' ]
[ 5, 0, 12 ]
{ apples: 5, plums: 12 }

Test yourself

How do you read a property whose name is stored in a variable key?

  1. obj.key
  2. obj[key]
  3. obj->key
  4. obj{key}
Show answer

Answer: obj[key]