Docs

README

7.1 Object Basics

Introduction

Objects are collections of key-value pairs where keys are strings (or Symbols) and values can be any type. They're the primary data structure in JavaScript for organizing and storing data.


Creating Objects

Object Literal (Most Common)

const person = {
  name: 'Alice',
  age: 30,
  isEmployed: true,
};

Empty Object

const empty1 = {};
const empty2 = new Object(); // Not recommended
const empty3 = Object.create(null); // No prototype

Object Constructor (Avoid)

// Not recommended - use literal instead
const obj = new Object();
obj.name = 'Bob';

Properties

Property Types

┌────────────────────────────────────────────────────────┐
│                   PROPERTY TYPES                        │
├────────────────────────────────────────────────────────┤
│                                                         │
│  DATA PROPERTIES                                        │
│  └── Store a value directly                             │
│      const obj = { name: "Alice" };                     │
│                                                         │
│  ACCESSOR PROPERTIES                                    │
│  └── Use get/set functions                              │
│      const obj = {                                      │
│          get name() { return this._name; },             │
│          set name(v) { this._name = v; }                │
│      };                                                 │
│                                                         │
│  METHODS                                                │
│  └── Properties that are functions                      │
│      const obj = { greet() { return "Hi"; } };          │
│                                                         │
└────────────────────────────────────────────────────────┘

Adding Properties

const user = {};

// Dot notation
user.name = 'Alice';

// Bracket notation
user['email'] = 'alice@example.com';

// Computed property name
const field = 'age';
user[field] = 30;

console.log(user);
// { name: "Alice", email: "alice@example.com", age: 30 }

Property Access

Dot Notation

const user = { name: 'Alice', age: 30 };

console.log(user.name); // "Alice"
console.log(user.age); // 30

Bracket Notation

const user = { name: 'Alice', 'full-name': 'Alice Smith' };

console.log(user['name']); // "Alice"
console.log(user['full-name']); // "Alice Smith" (can't use dot)

// With variables
const prop = 'name';
console.log(user[prop]); // "Alice"

When to Use Each

┌────────────────────────────────────────────────────────┐
│           DOT vs BRACKET NOTATION                       │
├────────────────────────────────────────────────────────┤
│                                                         │
│  USE DOT NOTATION when:                                 │
│  • Property name is a valid identifier                  │
│  • Property name is known at code-write time            │
│  • Property name doesn't contain special characters     │
│                                                         │
│  USE BRACKET NOTATION when:                             │
│  • Property name contains spaces or special chars       │
│  • Property name is stored in a variable                │
│  • Property name is computed dynamically                │
│  • Property name is a number                            │
│                                                         │
└────────────────────────────────────────────────────────┘

Computed Property Names (ES6)

const prefix = 'user';

const config = {
  [prefix + 'Name']: 'Alice',
  [prefix + 'Age']: 30,
  [`${prefix}Email`]: 'alice@example.com',
};

console.log(config.userName); // "Alice"
console.log(config.userAge); // 30
console.log(config.userEmail); // "alice@example.com"

With Expressions

const i = 0;

const items = {
  [`item${i}`]: 'first',
  [`item${i + 1}`]: 'second',
  [2 * 3]: 'at index 6',
};

console.log(items.item0); // "first"
console.log(items.item1); // "second"
console.log(items[6]); // "at index 6"

Shorthand Properties (ES6)

When variable name matches property name:

const name = 'Alice';
const age = 30;

// Old way
const user1 = { name: name, age: age };

// Shorthand (ES6)
const user2 = { name, age };

console.log(user2); // { name: "Alice", age: 30 }

Shorthand Methods (ES6)

// Old way
const obj1 = {
  greet: function () {
    return 'Hello';
  },
};

// Shorthand (ES6)
const obj2 = {
  greet() {
    return 'Hello';
  },
};

Checking for Properties

in Operator

const user = { name: 'Alice', age: 30 };

console.log('name' in user); // true
console.log('email' in user); // false
console.log('toString' in user); // true (inherited)

hasOwnProperty()

const user = { name: 'Alice' };

console.log(user.hasOwnProperty('name')); // true
console.log(user.hasOwnProperty('toString')); // false (inherited)

Checking for undefined

const user = { name: 'Alice', age: undefined };

// Be careful with undefined check!
console.log(user.age === undefined); // true
console.log(user.email === undefined); // true (but doesn't exist!)

// Better: use 'in' or hasOwnProperty
console.log('age' in user); // true
console.log('email' in user); // false

Deleting Properties

const user = { name: 'Alice', age: 30 };

delete user.age;

console.log(user); // { name: "Alice" }
console.log(user.age); // undefined

Property Order

Properties have a defined order:

const obj = {
  2: 'two',
  1: 'one',
  b: 'b',
  a: 'a',
};

console.log(Object.keys(obj));
// ["1", "2", "b", "a"]
// Integer keys sorted numerically, then string keys in insertion order

Nested Objects

const user = {
  name: 'Alice',
  address: {
    street: '123 Main St',
    city: 'Boston',
    zip: '02101',
  },
  contacts: {
    email: 'alice@example.com',
    phone: '555-1234',
  },
};

// Accessing nested properties
console.log(user.address.city); // "Boston"
console.log(user['contacts']['email']); // "alice@example.com"

Optional Chaining (?.)

Safely access nested properties:

const user = {
  name: 'Alice',
  // address property missing
};

// Without optional chaining - error!
// console.log(user.address.city); // TypeError!

// With optional chaining - safe
console.log(user.address?.city); // undefined

// Works with methods too
console.log(user.getName?.()); // undefined (method doesn't exist)

// Works with bracket notation
const prop = 'address';
console.log(user[prop]?.city); // undefined

Nullish Coalescing (??)

Provide default values:

const user = {
  name: 'Alice',
  age: 0, // falsy but valid
  nickname: '', // falsy but valid
};

// || treats 0 and "" as falsy
console.log(user.age || 25); // 25 (wrong!)
console.log(user.nickname || 'N/A'); // "N/A" (wrong!)

// ?? only uses default for null/undefined
console.log(user.age ?? 25); // 0 (correct!)
console.log(user.nickname ?? 'N/A'); // "" (correct!)
console.log(user.email ?? 'N/A'); // "N/A" (correct!)

Summary

ConceptSyntax
Object literal{ key: value }
Dot accessobj.key
Bracket accessobj["key"] or obj[variable]
Computed property{ [expr]: value }
Shorthand property{ name } (same as { name: name })
Shorthand method{ method() {} }
Check property"key" in obj or obj.hasOwnProperty("key")
Delete propertydelete obj.key
Optional chainingobj?.prop?.nested
Nullish coalescingvalue ?? default

Next Steps

In the next section, we'll explore Object Methods and this—how methods work and how this binding affects them.

README - JavaScript Tutorial | DeepML