CodeBlanks Logo Icon CodeBlanks

Defining a class

JavaScript course · Advanced · Lesson 7/100

Learn to define a class with the class keyword.

What is a class?

A class is a template used to create objects. In JavaScript it is declared with the class keyword and has a body between curly braces.

The template describes how to make objects; it is not an object itself. From one class you can create as many instances as you need.

Classes work like real-world molds: a 'User' class defines the shared structure for every user.

Class declaration

A class declaration starts with the class keyword, followed by the class name and a body in curly braces.

class User {
  // body goes here
}

Class names usually start with a capital letter (for example User, Product). The body can be empty; we will add methods and a constructor later.

A declaration does not create an object by itself; it only defines the template.

Exercise Empty-bodied class

Declare a class named Account with an empty body.

Show example solution
Start the class name with a capital letter.
Example solution:
class Account {}

Test yourself

  1. Which keyword declares a class in JavaScript?

    • function
    • class
    • object
    • struct
    Show answer

    class — Correct! The class keyword starts a class declaration.

  2. Complete the class declaration

    class ____ {
    }
    Show answer
    class User {
    }
  3. Match the concepts

    class
    declares a class
    { }
    class body
    class User {}
    empty-bodied class
    User
    class name

All lessons in Advanced