AnyCompiler

Objects

An object stores key-value pairs — JavaScript's equivalent of Python's dictionary. Instead of looking something up by position like an array, you look it up by a name you chose.

let person = { name: "Alice", age: 30, city: "NYC" };
console.log(person);
console.log(person.name);

person.age = 31;
console.log(person);

person.email = "alice@example.com";
console.log(person);

console.log(Object.keys(person));
console.log(Object.values(person));
Output
{ name: 'Alice', age: 30, city: 'NYC' }
Alice
{ name: 'Alice', age: 31, city: 'NYC' }
{ name: 'Alice', age: 31, city: 'NYC', email: 'alice@example.com' }
[ 'name', 'age', 'city', 'email' ]
[ 'Alice', 31, 'NYC', 'alice@example.com' ]
  • person.name (dot notation) reads the value stored under the key name — person["name"] (bracket notation) works too, and is required when the key is stored in a variable
  • Assigning to an existing key updates its value; assigning to a new key adds it — the same syntax does both
  • Object.keys() and Object.values() return every key or every value as an array, in insertion order

Next: sets — a collection that automatically removes duplicates.

Practice exercise

Create person = { name: "Alice", age: 30 }. Update age to 31, then print person.age.