0
0
Javascriptprogramming~15 mins

Object keys and values in Javascript - Deep Dive

Choose your learning style9 modes available
Overview - Object keys and values
What is it?
In JavaScript, objects store data as pairs of keys and values. Keys are like labels or names, and values are the data linked to those keys. You can think of an object as a collection of these labeled pieces of information. This lets you organize and access data easily by using the keys.
Why it matters
Without keys and values, it would be hard to organize data in a way that makes sense to humans and computers. Imagine a messy box with items but no labels; finding something would be slow and confusing. Object keys and values let programmers store and retrieve data quickly and clearly, making programs easier to write and understand.
Where it fits
Before learning about object keys and values, you should know basic JavaScript syntax and variables. After this, you can learn about more complex data structures like arrays, maps, and classes, which build on the idea of storing and organizing data.
Mental Model
Core Idea
An object is like a labeled container where each label (key) points to a piece of data (value).
Think of it like...
Think of an object like a filing cabinet where each drawer has a label (key) and inside is a folder with information (value). You open the drawer by its label to find the folder you want.
Object {
  ├─ key1: value1
  ├─ key2: value2
  ├─ key3: value3
  └─ ...
}

Access: object[key] or object.key
Build-Up - 7 Steps
1
FoundationWhat are object keys and values
🤔
Concept: Introduce the basic idea of keys and values in an object.
In JavaScript, an object is created using curly braces {}. Inside, you write keys and values separated by colons. For example: const person = { name: 'Alice', age: 30 }; Here, 'name' and 'age' are keys, and 'Alice' and 30 are their values.
Result
You get an object named person with two keys: 'name' and 'age', each holding a value.
Understanding that objects store data as key-value pairs is the foundation for working with structured data in JavaScript.
2
FoundationAccessing values using keys
🤔
Concept: Learn how to get the value stored under a key.
You can get a value from an object by using dot notation or bracket notation: console.log(person.name); // Outputs: Alice console.log(person['age']); // Outputs: 30 Dot notation is simpler but bracket notation lets you use variables as keys.
Result
You can read the value 'Alice' by using person.name and the value 30 by person['age'].
Knowing how to access values by keys lets you retrieve specific data from objects easily.
3
IntermediateAdding and changing keys and values
🤔
Concept: Objects are dynamic; you can add or update keys anytime.
You can add a new key or change an existing one: person.city = 'New York'; person.age = 31; Now person has a new key 'city' with value 'New York', and 'age' is updated to 31.
Result
The object person now has three keys: name, age (updated), and city (new).
Objects are flexible containers that can grow or change as your program runs.
4
IntermediateListing all keys or values
🤔Before reading on: do you think JavaScript objects keep keys in a fixed order? Commit to your answer.
Concept: Learn how to get all keys or all values from an object.
JavaScript provides Object.keys() and Object.values() to get arrays of keys or values: const keys = Object.keys(person); // ['name', 'age', 'city'] const values = Object.values(person); // ['Alice', 31, 'New York'] Keys are usually in the order they were added, but this can vary.
Result
You get arrays listing all keys and all values in the object.
Being able to list keys or values helps when you want to process or display all data in an object.
5
IntermediateUsing keys as variables with bracket notation
🤔Before reading on: can you use a variable to access an object’s value with dot notation? Commit to your answer.
Concept: Bracket notation lets you use variables to access keys dynamically.
If you have a variable holding a key name, you must use bracket notation: const keyName = 'city'; console.log(person[keyName]); // Outputs: New York Dot notation (person.keyName) looks for a key literally named 'keyName', which doesn’t exist.
Result
You can access values dynamically using variables as keys.
Understanding bracket notation is essential for dynamic programming where keys are not fixed.
6
AdvancedKeys as strings or symbols only
🤔Before reading on: can object keys be numbers or other types besides strings? Commit to your answer.
Concept: Object keys are always strings or symbols; other types convert to strings.
If you use a number as a key, JavaScript converts it to a string: const obj = { 1: 'one', true: 'yes' }; console.log(Object.keys(obj)); // ['1', 'true'] Symbols are a special type of key that don’t convert to strings and are unique.
Result
Keys are stored as strings or symbols, never as other types.
Knowing key types prevents bugs when using numbers or booleans as keys.
7
ExpertHidden keys and property descriptors
🤔Before reading on: do all object keys show up in Object.keys()? Commit to your answer.
Concept: Some keys are hidden or non-enumerable and don’t appear in normal key lists.
JavaScript objects have property descriptors controlling if keys are enumerable, writable, or configurable. For example, keys created with Object.defineProperty can be hidden: Object.defineProperty(person, 'secret', { value: 'hidden', enumerable: false }); console.log(Object.keys(person)); // 'secret' is missing But you can still access person.secret directly.
Result
Not all keys are visible with Object.keys(); some are hidden by design.
Understanding property descriptors helps manage object keys carefully in complex programs.
Under the Hood
JavaScript objects are implemented as hash maps internally. When you add a key-value pair, the key (converted to a string or symbol) is hashed to find a storage slot. Accessing a value uses the key's hash to quickly locate the value. Property descriptors add metadata controlling visibility and mutability of keys. This design balances fast access with flexibility.
Why designed this way?
Objects needed to be fast for common operations like reading and writing keys, so hash maps were chosen. Using strings as keys fits JavaScript’s dynamic nature. Property descriptors were added later to allow more control over object properties, enabling features like hiding keys or making them read-only.
Object Storage
┌─────────────────────────────┐
│ Keys (strings/symbols)       │
│ ┌───────────────┐           │
│ │ 'name'        │──┐        │
│ │ 'age'         │  │ Hash   │
│ │ 'city'        │  │ Map    │
│ │ 'secret' (non-enum) │     │
│ └───────────────┘  │        │
│                    │        │
│ Values             │        │
│ ┌───────────────┐  │        │
│ │ 'Alice'       │◄─┘        │
│ │ 31            │           │
│ │ 'New York'    │           │
│ │ 'hidden'      │           │
│ └───────────────┘           │
└─────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do object keys keep the order you add them in all cases? Commit to yes or no.
Common Belief:Object keys always keep the order they were added.
Tap to reveal reality
Reality:JavaScript objects keep keys in insertion order only for string keys that are not integer indices. Integer-like keys are sorted numerically first.
Why it matters:Assuming keys keep insertion order can cause bugs when iterating over objects with numeric keys, leading to unexpected order.
Quick: Can you use any data type as an object key without conversion? Commit to yes or no.
Common Belief:You can use numbers, booleans, or objects directly as keys without changes.
Tap to reveal reality
Reality:All keys except symbols are converted to strings. Using objects as keys converts them to '[object Object]', causing collisions.
Why it matters:Misunderstanding this leads to overwriting keys unintentionally and data loss.
Quick: Does Object.keys() list all keys in an object? Commit to yes or no.
Common Belief:Object.keys() returns every key in the object.
Tap to reveal reality
Reality:Object.keys() returns only enumerable keys; non-enumerable keys are hidden.
Why it matters:Relying on Object.keys() alone can miss important keys, causing incomplete data processing.
Quick: Can you access object keys using dot notation with variables? Commit to yes or no.
Common Belief:Dot notation works with variables holding key names.
Tap to reveal reality
Reality:Dot notation treats the name literally; only bracket notation works with variables.
Why it matters:Using dot notation with variables causes bugs where keys are not found.
Expert Zone
1
Keys that look like numbers are treated specially and sorted before other keys during iteration.
2
Symbols as keys are not included in Object.keys() or for...in loops but can be retrieved with Object.getOwnPropertySymbols().
3
Property descriptors allow fine control over keys, enabling patterns like read-only or hidden properties.
When NOT to use
For complex key types or when keys are not strings or symbols, use Map instead of plain objects. Maps allow any value as keys without conversion and preserve insertion order strictly.
Production Patterns
Objects are used for configuration, storing related data, and representing entities. Developers often combine objects with destructuring, spread syntax, and property descriptors for clean, maintainable code.
Connections
Hash maps
Objects are a type of hash map data structure.
Understanding hash maps explains why object key lookup is fast and why keys must be strings or symbols.
Maps (JavaScript Map object)
Maps build on objects by allowing any type as keys and preserving insertion order strictly.
Knowing the limits of object keys helps decide when to use Map for more flexible key-value storage.
Dictionaries in natural language processing
Both store pairs of keys and values to represent meaning or data.
Seeing objects as dictionaries connects programming data structures to how humans organize knowledge.
Common Pitfalls
#1Using dot notation with a variable key name.
Wrong approach:const key = 'name'; console.log(person.key); // undefined
Correct approach:const key = 'name'; console.log(person[key]); // 'Alice'
Root cause:Dot notation treats 'key' literally, not as a variable holding the key name.
#2Assuming Object.keys() lists all keys including hidden ones.
Wrong approach:Object.defineProperty(person, 'secret', { value: 'hidden', enumerable: false }); console.log(Object.keys(person)); // ['name', 'age', 'city'] (missing 'secret')
Correct approach:console.log(Object.getOwnPropertyNames(person)); // ['name', 'age', 'city', 'secret']
Root cause:Object.keys() only lists enumerable keys, missing non-enumerable ones.
#3Using objects as keys in plain objects expecting unique keys.
Wrong approach:const objKey = {}; const obj = {}; obj[objKey] = 'value'; console.log(obj['[object Object]']); // 'value'
Correct approach:const objKey = {}; const map = new Map(); map.set(objKey, 'value'); console.log(map.get(objKey)); // 'value'
Root cause:Objects convert to the same string '[object Object]' as keys, causing collisions.
Key Takeaways
JavaScript objects store data as key-value pairs where keys are strings or symbols.
You access values using dot notation for fixed keys or bracket notation for dynamic keys.
Object keys are usually enumerable strings, but some keys can be hidden using property descriptors.
Not all keys behave the same: numeric keys are sorted, symbols are hidden, and objects as keys require Maps.
Understanding these details helps avoid common bugs and choose the right data structure for your needs.