Skip to content
  • Objects · JavaScript

Objects

LearnViaNotes @learnvianotes· 2 min read

Objects are collections of key → value properties. Keys are strings or symbols; values can be anything, including functions (methods).

Object literals, modern syntax

JavaScript
const name = "Asha", age = 28;
const field = "email";
const user = {
  name,                                  // shorthand for name: name
  age,
  [field]: "asha@example.com",           // computed key
  [`is${"Admin"}`]: false,
  "full name": "Asha Rao",               // any string can be a key
  greet() { return `Hi, ${this.name}`; },  // method shorthand
};
console.log(user);
console.log(user.greet(), user["full name"], user[field]);
Output
{
  name: 'Asha',
  age: 28,
  email: 'asha@example.com',
  isAdmin: false,
  'full name': 'Asha Rao',
  greet: [Function: greet]
}
Hi, Asha Asha Rao asha@example.com

Reading, writing, deleting, checking

JavaScript
const car = { brand: "Tata", year: 2020 };
car.color = "red";           // add
car.year = 2021;             // update
delete car.brand;            // remove
console.log(car);
console.log("color" in car, Object.hasOwn(car, "color"), car.speed);
console.log("toString" in car, Object.hasOwn(car, "toString"));
Output
{ year: 2021, color: 'red' }
true true undefined
true false
CheckOwn propsInherited propsValue undefined counts?
obj.key !== undefinedYesYesNo — misses explicit undefined
'key' in objYesYesYes
Object.hasOwn(obj, 'key')YesNoYes

Keys are strings (or symbols)

JavaScript
const obj = {};
obj[1] = "number key";
obj[{}] = "object key";
console.log(Object.keys(obj), obj["1"]);
const order = { b: 1, 2: "two", a: 2, 1: "one" };
console.log(Object.keys(order));
Output
[ '1', '[object Object]' ] number key
[ '1', '2', 'b', 'a' ]

Getters and setters

JavaScript
const temperature = {
  celsius: 25,
  get fahrenheit() {
    return this.celsius * 9 / 5 + 32;
  },
  set fahrenheit(f) {
    this.celsius = Math.round((f - 32) * 5 / 9);
  },
};
console.log(temperature.fahrenheit);
temperature.fahrenheit = 212;
console.log(temperature.celsius, temperature);
Output
77
100 { celsius: 100, fahrenheit: [Getter/Setter] }

Iterating an object

JavaScript
const scores = { math: 90, art: 75, music: 88 };
for (const [subject, score] of Object.entries(scores)) {
  console.log(`${subject.padEnd(6)} ${score}`);
}
const total = Object.values(scores).reduce((a, b) => a + b, 0);
console.log(total, Object.keys(scores).length);
Output
math   90
art    75
music  88
253 3

How do you check if an object is empty?

Difference between dot and bracket notation?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report