JavaScript | class expression

JavaScript class is a type of function declared with class keyword, that is used to implement object-oriented paradigm. Constructors are used to initialize the attributes of a class. There are 2 ways to creating class in JavaScript.

  • class declaration
  • class expression

In this article, we’ll discuss class expression to declare classes in JavaScript and how to use them.

class expression:  The class expression is another way of creating classes in JavaScript and they can be named or unnamed. If named, the class name is used internally, but not outside of the class.

Syntax:

  • Using named class expression:
const variable_name = new Class_name {
    // class body
}
  • Using unnamed class expression:
const variable_name = class{
     //class body
}

Example 1: Named class expression:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
const Website = class Geek {
  constructor(name){
      this.name = name;
  }
  websiteName() {
    return this.name;
  }
};
  
const x = new Website("GeeksforGeeks");
console.log(x.websiteName());
</script>

chevron_right


Output:



GeeksforGeeks

Example 2: Unnamed class expression:

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
const Website = class {
  constructor(name) {
    this.name = name;
  }
  returnName() {
    return this.name;
  }
};
  
console.log(new Website("GeeksforGeeks").returnName());
</script>

chevron_right


Output:

GeeksforGeeks

full-stack-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.