Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavascriptJavaScript class expression

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




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


Output:

neveropen

Example 2: Unnamed class expression:

Javascript




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


 
 

Output:

 

neveropen

 

Supported Browser:

  • Chrome 42 and above
  • Edge 13 and above
  • Firefox 45 and above
  • Opera 29 and above
  • Safari 7 and above
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments