Simple Class in JavaScript

Level 4184 keystrokes

This defines a Person class with a constructor and method, then creates an instance.

JavaScript code

// class keyword defines a class
1class Person {
// constructor is called when creating a new instance
// It initializes the object's properties
2 constructor(name, age) {
// this refers to the current instance
3 this.name = name;
4 this.age = age;
5 }
6
// Methods are functions attached to the class
7 greet() {
// Template literal uses this.name
8 return `Hello, I'm ${this.name}`;
9 }
10}
11
// new creates an instance of the class
12const p = new Person("Alice", 25);
// Call the greet method on the instance
13console.log(p.greet());

Output

Hello, I'm Alice
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this JavaScript code and how often they appear.

  • ;× 5
  • .× 5
  • (× 5
  • )× 5
  • {× 4
  • }× 4
  • ,× 3
  • =× 3
  • "× 2
  • `× 2

More JavaScript examples at level 4

← JavaScript typing practice