DEV Community


Use class Syntax to Define a Constructor Function

rthefounding profile image Randy Rivera ・1 min read
  • ES6 provides a new syntax to create objects, using the class keyword. It should be noted that the class syntax is just syntax, and not a full-fledged class-based implementation of an object-oriented paradigm, unlike in languages such as Java, Python, Ruby, etc.
  • In ES5, we usually define a constructor function and use the new keyword to instantiate an object.
var Vegetable = function(name){ = name;
var carrot = new Vegetable('carrot');
Enter fullscreen mode Exit fullscreen mode
  • The class syntax simply replaces the constructor function creation.
class Vegetable {
  constructor(name) { = name;

const carrot = new Vegetable('carrot');
console.log(; // Should display 'carrot'
Enter fullscreen mode Exit fullscreen mode

It should also be noted that the class keyword declares a new function, to which a constructor is added. This constructor is invoked when new is called to create a new object.

  • Note: UpperCamelCase should be used by convention for ES6 class names, as in SpaceShuttle used above.

Discussion (0)

Forem Open with the Forem app