Class Syntax within a function and without

Tell us what’s happening:
In the example, we create a new object by using ‘new’ keyword directly to the class but in the problem we are shown to create the class inside a function and call ‘new’ keyword on that function to initialize the object. Can anyone tell me why we are doing this? Is there any difference between these two ways?

Your code so far

function makeClass() {
  "use strict";
  /* Alter code below this line */
    class Vegetable {
      constructor(name) {
        this.name = name;
      }
    }
  /* Alter code above this line */
  return Vegetable;
}
const Vegetable = makeClass();
const carrot = new Vegetable('carrot');
console.log(carrot.name); // => should be 'carrot'

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36.

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

The only difference is that makeClass is a function that returns a Class. The challenge doesn’t take that in consideration. in fact you don’t need that to pass the challenge.

In fact that’s all it takes for you to pass the challenge:

class Vegetable {
  constructor(name) {
    this.name = name;
  }
}

const carrot = new Vegetable('carrot');

The purpose is to show you that a class can also be used as a functions’ return.

1 Like