Objects

Updated · 7 min read
mediumES2026javascriptobjectspropertiesinterview

An object in JavaScript is a collection of properties, where each property is a key (a name) paired with a value. Objects model the things a program deals with: a student has a name, a grade and a balance; a payment has an amount, a date and a method. Nearly everything in JavaScript that isn't a primitive is an object, including arrays, functions and dates, so knowing how objects work is knowing how the language works.

In One Minute

  • Create objects with braces: const student = { name: "Navika", grade: 9 };.
  • Read and write properties with a dot (student.name) or brackets (student["name"], needed for keys in variables).
  • Shorthand ({ name, grade }) and computed ({ [key]: value }) properties make literals shorter and dynamic.
  • Add a property by assigning it; remove one with delete.
  • Check for a property with Object.hasOwn(obj, key) or key in obj; don't rely on obj.key !== undefined.

Creating Objects

Syntax

syntax.js
const object = {
  key1: value1,
  key2: value2,
};

Example

literal.js▶ Try it
const student = {
  name: "Navika Anamaneni",
  grade: 9,
  city: "Dallas",
  isEnrolled: true,
  fees: [400, 85],
  guardian: { name: "Srihitha Anamaneni", phone: "2145550100" },
};
 
console.log(student.name);
console.log(student.fees[1]);
console.log(student.guardian.name);
console.log(typeof student);
Output
Navika Anamaneni
85
Srihitha Anamaneni
object

Values can be anything: strings, numbers, booleans, arrays, other objects, functions. Keys are strings (or symbols). The trailing comma after the last property is allowed and makes adding properties later cleaner.

Dot vs Bracket Notation

NotationExampleWhen
Dotstudent.gradeThe key is a fixed, valid identifier. Use it by default.
Bracketstudent["grade"]The key is in a variable, has spaces or dashes, or starts with a digit.
access.js▶ Try it
const record = { name: "Advitha", "due date": "02/01/2026", 2026: 450 };
 
const field = "name";
console.log(record[field]);
console.log(record["due date"]);
console.log(record[2026]);
console.log(record.field);
Output
Advitha
02/01/2026
450
undefined

Explanation: record[field] evaluates the variable field and reads the property called "name". record.field reads a property literally named "field", which doesn't exist. Numbers used as keys are converted to strings: record[2026] and record["2026"] are the same property.

Shorthand and Computed Properties

Shorthand properties (ES2015): when a property's value comes from a variable with the same name, write the name once.

Computed properties: put an expression in brackets to use its value as the key.

shorthand.js▶ Try it
const name = "Srihitha";
const grade = 11;
const student = { name, grade };
console.log(student);
 
const field = "balance";
const term = "fall";
const update = { [field]: 85, [`${term}Fee`]: 450 };
console.log(update);
Output
{ name: 'Srihitha', grade: 11 }
{ balance: 85, fallFee: 450 }

Shorthand is everywhere in modern code, especially when returning several values: return { total, count, average };.

Adding, Changing and Deleting Properties

Objects are open: assign to a property that doesn't exist and it is created. delete removes a property:

change.js▶ Try it
const payment = { amount: 120 };
 
payment.method = "card";
payment.amount = 125;
console.log(payment);
 
delete payment.method;
console.log(payment);
console.log(payment.method);
Output
{ amount: 125, method: 'card' }
{ amount: 125 }
undefined

const doesn't prevent any of this; it only stops payment from being pointed at a different object. In modern code, prefer creating a new object without the property instead of delete: const { method, ...rest } = payment;. That keeps the original intact, and engines optimize objects better when their shape doesn't change.

Checking Whether a Property Exists

Reading a missing property gives undefined, so obj.key !== undefined looks like a test for existence. It isn't, because a property can exist and hold undefined:

exists.js▶ Try it
const student = { name: "Advitha", phone: undefined };
 
console.log(student.phone !== undefined);
console.log("phone" in student);
console.log(Object.hasOwn(student, "phone"));
 
console.log("toString" in student);
console.log(Object.hasOwn(student, "toString"));
Output
false
true
true
true
false
CheckTrue when
obj.key !== undefinedThe value isn't undefined (misses properties set to undefined)
"key" in objThe property exists on the object or its prototype chain
Object.hasOwn(obj, "key")The property exists on the object itself (ES2022)

Explanation: "toString" in student is true because every object inherits toString from Object.prototype (prototypes have their own lesson later). Object.hasOwn looks only at the object's own properties, which is usually what you mean. It replaces the older obj.hasOwnProperty("key").

Property Order

Object properties have a defined order: integer-like keys first, in ascending order, then string keys in the order they were added:

order.js▶ Try it
const fees = { fall: 450, 12: 445, spring: 400, 9: 400 };
console.log(Object.keys(fees));
Output
['9', '12', 'fall', 'spring']

If you need a guaranteed custom order, use an array or a Map.

In Practice

The Fee Tracker builds a student record from form fields, using shorthand properties, a computed key for the current term, and a safe existence check before applying an optional discount:

record.js▶ Try it
const DISCOUNTS = { sibling: 0.1, staff: 0.5 };
 
function buildRecord(form, term) {
  const { name, grade, discountCode } = form;
  const fee = 450;
  const rate = Object.hasOwn(DISCOUNTS, discountCode) ? DISCOUNTS[discountCode] : 0;
  return {
    name,
    grade: Number(grade),
    [`${term}Fee`]: fee * (1 - rate),
    discount: rate > 0 ? discountCode : null,
  };
}
 
console.log(buildRecord({ name: "Navika", grade: "9", discountCode: "sibling" }, "fall"));
console.log(buildRecord({ name: "Advitha", grade: "11", discountCode: "toString" }, "spring"));
Output
{ name: 'Navika', grade: 9, fallFee: 405, discount: 'sibling' }
{ name: 'Advitha', grade: 11, springFee: 450, discount: null }

With DISCOUNTS[discountCode] alone, the code "toString" would have found the inherited function, and the fee would have become NaN.

Common Mistakes

Dot notation with a variable key. obj.key reads "key". Use obj[key].

Testing existence with !== undefined. Misses properties set to undefined. Use Object.hasOwn.

Using objects as dictionaries for user-supplied keys. Inherited names (toString, __proto__) can collide. Use Object.hasOwn, Object.create(null), or a Map.

Expecting const to freeze an object. It doesn't. Use Object.freeze (protecting objects lesson).

Interview Corner

What is the difference between dot and bracket notation?

Dot notation takes a literal identifier: obj.name reads the property "name". Bracket notation evaluates an expression and converts it to a property key: obj[key] reads the property named by key's value. Brackets are required for keys that aren't valid identifiers (spaces, dashes, leading digits) and for keys held in variables or symbols.

How do you check whether an object has a property?

Object.hasOwn(obj, key) for own properties (ES2022, preferred over obj.hasOwnProperty). key in obj also checks the prototype chain. Comparing to undefined fails for properties that exist with the value undefined.

What does this print?

Show solution
puzzle.js▶ Try it
const key = "grade";
const s = { key: 1, [key]: 2, grade: 3 };
console.log(s.key, s[key], Object.keys(s).length);
Output
1 3 2

key: 1 creates a property named "key". [key]: 2 creates "grade", which grade: 3 then overwrites, because a later duplicate key wins. Two properties remain.

Practice

Challenge: Write pick(obj, keys) that returns a new object with only the listed keys that obj actually has, so pick({ a: 1, b: 2, c: 3 }, ["a", "c", "z"]) gives { a: 1, c: 3 }.

Show solution
pick.js▶ Try it
function pick(obj, keys) {
  const result = {};
  for (const key of keys) {
    if (Object.hasOwn(obj, key)) result[key] = obj[key];
  }
  return result;
}
 
console.log(pick({ a: 1, b: 2, c: 3 }, ["a", "c", "z"]));
console.log(pick({ name: "Srihitha", balance: 85 }, ["name"]));
Output
{ a: 1, c: 3 }
{ name: 'Srihitha' }

Quick check: Objects

3 questions
1With const field = "city", how do you read the city property?
2What does { name } mean inside an object literal when a variable name exists?
3Which check is true only for the object's own properties?

Key Takeaways

TaskCode
Create{ name: "Navika", grade: 9 }
Dynamic keyobj[key], { [key]: value }
Shorthand{ name, grade }
Removedelete obj.key or const { key, ...rest } = obj
Own property?Object.hasOwn(obj, "key")

Was this tutorial helpful?

Lesson 37 of 139