YogeshChauhan.com

The difference between Class declarations and Class expressions in JavaScript

March 8, 2021

Class declarations and Class expressions are different ways of defining classes in JavaScript.

Class declarations

We use the keyword class to declare a class. Just like this:


class Person {
  constructor(name, birthDate) { 
    this.name = name;
    this.birthDate = birthDate;
  }
}

Function declarations are hoisted. Class declarations are NOT hoisted. That means we need to declare the class before trying to access it or we’ll get a ReferenceError.

Class expressions

Class expressions can be named or without a name.

Named Class expressions Example


// named
let Person = class PersonClassNamed {
  constructor(name, birthDate) { 
    this.name = name;
    this.birthDate = birthDate;
  }
};
console.log(Person.name);
// output: "PersonClassNamed"

Unnamed Class expressions Example


// without a name
let Person = class {
  constructor(name, birthDate) { 
    this.name = name;
    this.birthDate = birthDate;
  }
};
console.log(Person.name);
// output: "Person"

The hoisting restrictions applies to Class expressions.

MDN has a good documentation on this.

dreamhost

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to uninstall Cocoapods from the Mac OS? #4 How to Use SQL MAX() Function with Dates? #5 How to add Read More Read Less Button using JavaScript? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Apr 7 Solution for “Yarn build: Failed because of a stylelint error” Apr 7 Make sure your links have descriptive text Apr 7 How to add Laravel to WordPress using Sage theme (and install Tailwind CSS)? Apr 2 How to create a sidebar using pure CSS? Apr 1 How to switch dark and light themes using pure CSS? Apr 1 How to calculate elapsed time in JavaScript?

You might also like these

Containers 101: What are containers?MiscHow to Commit and Rollback Changes in SQL?SQL/MySQLHow to implement NSNumberFormatter in Swift for currency?SwiftHAVING Clause in Postgres with Examples in All Aggregate FunctionsPostgresinclude, include_once, require, require_once in PHPPHPJavaScript: Methods for HTML DOM classList PropertyJavaScriptSQL ANY OperatorSQL/MySQLHow to insert Bootstrap 4 in Angular 9 app?AngularHow to apply style to a specific child element using CSS?CSSHow to make a UILabel clickable in Swift 5?SwiftA complete diagram with building blocks of an Angular applicationAngularHow to Create a Copy of a Table in SQL and MySQL?SQL/MySQL