0
0
Javascriptprogramming~5 mins

Object keys and values in Javascript

Choose your learning style9 modes available
Introduction

We use object keys and values to store and organize information in pairs, like labels and their details.

When you want to store information about a person, like name and age.
When you need to group related data, like settings for an app.
When you want to look up a value quickly using a label.
When you want to change or add information easily by key.
Syntax
Javascript
const obj = {
  key1: 'value1',
  key2: 'value2'
};

// To get keys:
Object.keys(obj);

// To get values:
Object.values(obj);

Keys are always strings or symbols, values can be any type.

Object.keys() returns an array of keys, Object.values() returns an array of values.

Examples
This shows keys ['name', 'age'] and values ['Alice', 30].
Javascript
const person = {
  name: 'Alice',
  age: 30
};

console.log(Object.keys(person));
console.log(Object.values(person));
Gets keys ['darkMode', 'fontSize'] and values [true, 16].
Javascript
const settings = {
  darkMode: true,
  fontSize: 16
};

const keys = Object.keys(settings);
const values = Object.values(settings);

console.log(keys);
console.log(values);
Sample Program

This program creates a car object and prints its keys and values.

Javascript
const car = {
  brand: 'Toyota',
  year: 2022,
  color: 'red'
};

console.log('Keys:', Object.keys(car));
console.log('Values:', Object.values(car));
OutputSuccess
Important Notes

Keys order is the same as they were added in most cases.

Values can be any type: strings, numbers, booleans, objects, etc.

Summary

Objects store data in key-value pairs.

Use Object.keys() to get all keys as an array.

Use Object.values() to get all values as an array.