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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to create a Child Theme in WordPress?WordPressHow to detect the Blog Page in WordPress?WordPressHow to insert Bootstrap 4 in Angular 9 app?AngularSome EASY-to-Understand CSS media query examplesCSSJavaScript Number MethodsJavaScriptHow to center an image horizontally and vertically?CSSModules and its Core features in JavaScriptJavaScriptAlternate Style Sheets in CSSCSSLearn to make a responsive gallery using CSS Grid and without media queriesCSSIf statement shorthand examples in JavaScriptJavaScriptHow to verify your domain in Google Console with a TXT record?MiscellaneousHow to auto-resize textarea based on text input using JavaScript or jQuery?JavaScript