YogeshChauhan . com

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.

amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

What is IPS(Intrusion Prevention System), How Does It Work and What are the Detection Types?MiscSome Useful Operators in The SQL WHERE ClauseSQL/MySQLHow to merge arrays in JavaScript?JavaScriptHow to Sort (Shuffle) an Array in Random Order in JavaScript?JavaScriptAlways add associated labels to your Form elementsUI/UXWordPress: How to find all posts with a specific custom field value?WordPressHow to Install PHP Laravel on MacOS Catalina?PHPHow to Secure Web or Mobile Browsers?MiscA simple example on grid ‘auto-fill’ vs ‘auto-fit’CSSThe 8 Golden Rules of Programming I Have Learned in My CareerMiscHow to create rotating texts using JavaScript and CSS?CSSDifferent Types of Functions in JavaScriptJavaScript