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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

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
Casting in PostgreSQLPostgresRendering Elements in ReactReactWhat is the difference between Loosely Typed Language and Strongly Typed Language?MiscellaneousMicroservices vs Monolithic ArchitectureMiscellaneous3 Types of Arrays in PHPPHPA Quick Guide to Object-Oriented Programming in PHPPHPA simple example on grid ‘auto-fill’ vs ‘auto-fit’CSSWhat are Controlled Components in React?ReactWordPress plugin development: How to fix a SQL injection?WordPressWordPress: How to access first and random row values from a repeater field in ACF?WordPressWhat is Host Hardening and What are some Important Hardening Steps?MiscellaneousHow to Draw a Text Image using JavaScript?JavaScript