Yogesh Chauhan's Blog

The difference between Class declarations and Class expressions in JavaScript

in JavaScript on 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.


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 add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Use eq() method in jQueryjQueryWhat are Stored Procedures for SQL Server?SQL/MySQL$this Keyword in PHPPHPHow to use data-* Attributes in HTML?HTMLHow to add Lifecycle Methods to a Class in React?ReactActions vs. Filters: hooks in WordPressWordPressRecursion in JavaScriptJavaScriptWhy does MOV matter in IT or any kind of projects?MiscellaneousList of social media icon logo color codes in HEXMiscellaneousHow to apply style to the first-child using jQuery?jQueryHow to add menu to your WordPress theme?WordPressWhat is Hadoop and Hadoop Ecosystem?Miscellaneous