Defining a class
- JavaScript course
- Advanced
- Lesson 7/100
- 5 min
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.
Practice Empty-bodied class
Declare a class named Account with an empty body.
Starter code
// declare the Account classSample solution
class Account {}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which keyword declares a class in JavaScript?
- function
- object
- class Correct answer
- struct
Explanation: The class keyword starts a class declaration.
2 Complete the class declaration
class ____ {
}
class User {
}
Explanation: class User {} is a valid class declaration.
3 Match the concepts
| Term | Meaning |
|---|---|
class |
declares a class |
{ } |
class body |
class User {} |
empty-bodied class |
User |
class name |