Do you need a constructor every time you use Class syntax?

Tell us what’s happening:

If Class defines a new function, what’s the purpose of this constructor thing? Do you need a constructor every time you use class? If not, then when should you and shouldn’t you use constructor?
Also, what is the “this.” thing do?

Your code so far


/* Alter code below this line */
class Vegetable {
constructor(name) {
    this.name = name;
}
}
/* Alter code above this line */

const carrot = new Vegetable('carrot');
console.log(carrot.name); // => should be 'carrot'

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.2 Safari/605.1.15.

Challenge: Use class Syntax to Define a Constructor Function

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/es6/use-class-syntax-to-define-a-constructor-function

A constructor is used to initialize a newly created object of the corresponding class. You are not required to define a constructor as in your example.

class Example {
  sayHi() {
    console.log('Hello there');
  }
}

let a = new Example();
a.sayHi(); \\ logs Hello there

If your object requires any initialization, the constructor is generally the appropriate place to do it.

1 Like

It’s the calling object: the new keyword creates an object out of thin air, the class is basically a template for that object, and this is used to refer to the object that will be created.

So this.name is a property called name on the object you create by running new Vegetable. Like new Vegetable("carrot") creates an object of datatype

[object Vegetable]

That looks like

{
  name: "carrot"
}

Understanding how this works is pretty critical w/r/t JavaScript

1 Like