CodeBlanks Logo Icon CodeBlanks

Creating objects

JavaScript course · Beginner · Lesson 71/133

Learn to create objects with key-value pairs using object literals.

Object literal

In JavaScript, an object groups several values into one container. Each value is labeled with a key, written as a key-value pair.

You create an object literal with curly braces:

const user = {
  name: 'Alex',
  age: 28
};

Here name and age are keys; 'Alex' and 28 are their values. Keys are usually written without quotes.

Different types in properties

An object's values can be of different data types: string, number, boolean, array, even another object.

const product = {
  name: 'Pen',
  price: 25,
  inStock: true,
  tags: ['stationery', 'office']
};

Each property keeps its own type. price is a number, inStock is a boolean, and tags is an array. This flexibility makes objects ideal for modeling real-world data.

Exercise Create a book object

Create an object named book. It should have title set to 'Lord of the Rings', pages set to 1178 and read set to false.

Show example solution
const book = {
  title: 'Lord of the Rings',
  pages: 1178,
  read: false
};

Test yourself

  1. Which is a valid object literal?

    // A
    const a = [1, 2, 3];
    // B
    const b = { name: 'Alex' };
    // C
    const c = (name: 'Alex');
    // D
    const d = < name: 'Alex' >;
    • A
    • B
    • C
    • D
    Show answer

    B — Correct! Curly braces form an object literal.

  2. Create an empty object

    const empty = ____;
    Show answer
    const empty = {};
  3. Match keys to their values

    name
    'Alex'
    age
    28
    active
    true

All lessons in Beginner