Skip to main content

Key-value

The "key-value" pair (key-value) is the foundation of data storage in JavaScript objects (and in many other structures). The key is the property name, the value is the data that corresponds to that name.


Detailed explanation

In JavaScript, an object stores data as a set of such pairs:

javascript
const user = { name: 'Tim', // key → value age: 25, city: 'Berlin' };

Here:

  • name, age, city are the keys (or "property names"),
  • 'Tim', 25, 'Berlin' are the values.

Each property is a key-value pair that describes a piece of data.


How keys work

  • Keys are always unique within a single object.

  • They are usually strings (or Symbols), even if you write a number:

    javascript
    const obj = { 1: 'a', 2: 'b' }; console.log(Object.keys(obj)); // ["1", "2"]

How to get a value by key

javascript
console.log(user.name); // "Tim" console.log(user['city']); // "Berlin"

Access is possible:

  • via dot notation, if the name is known in advance;
  • via brackets, if the key is stored in a variable.
javascript
const key = 'age'; console.log(user[key]); // 25

What key-value pairs consist of

You can see them as an array:

javascript
console.log(Object.entries(user));

Output:

javascript
[ ['name', 'Tim'], ['age', 25], ['city', 'Berlin'] ]

Each pair is [key, value].


Where else the "key-value" principle appears

StructureExampleWhat it stores
Object{ name: 'Tim' }Keys → strings
Mapmap.set('role', 'admin')Keys → any type
URLSearchParams?id=1&name=TimKeys and values from a URL string
FormDataform.append('email', 'tim@example.com')Form fields

SUMMARY

ElementDescription
KeyThe property name used to access the data
ValueThe data associated with that key
Example{ "key": "value" }
Typical storage format{ name: 'Tim', age: 25 }

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.