Use class Syntax to Define a Constructor Function I have a question a bout 'class'

Tell us what’s happening:
I need to understand more about the class, what it is used for, and what role does the ‘constructor’ have?

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; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) coc_coc_browser/77.0.126 Chrome/71.0.3578.126 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

  • A class is a description of how to create an object of a specific type.
  • The constructor is the function that you call to make that object.

And it might be helpful to think of this in the definition of the class as a placeholder for the object that will be created. So with your example, if you create a new Vegetable, this refers to that new vegetable object you just created, and that object has a property “name”.

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

So there, you have a description of how to create that object. It will just have a property name, so the thing you are creating looks like this:

{ name: /* whatever name you gave it */ }

The constructor function is just a JS function: it’s the thing you use to create the object. It is also where you can pass things in to configure how you want to create it, in this case you want to specify the name.

So

const carrot = new Vegetable("carrot")

Is saying "make a new object of the type Vegetable, assign ‘carrot’ to the object’s name property, and assign that new object to a variable carrot". The variable carrot now refers to this thing:

{ name: "carrot" }

Note that this basically does the same thing:

function createVegetable (name) {
  return { name: name };
}

The differences mainly come down to Object Oriented vs. Procedural programming styles. And note the most obvious difference is that when you add methods to classes (functions on the attached to the object), those methods get shared between all members of the class, and you can make child classes that inherit from parent classes and get access to all those methods.

edit: note that JS does not really have “classes” in the sense of other languages, the syntax here is just to make it look more like those other class-based languages (though the end result is much the same). So if you’re ever reading up on OO programming/class-based programming, be aware JS doesn’t work the same way

3 Likes

So, I heard that each class will have only one ‘constructor’ inside it? Is this right?

Yes, it would make no sense to have more than one: it is the function that creates the object.

1 Like

yeah, i got it, thanks

1 Like

// My question

Well, I’m having trouble because I don’t know how the above code works, can you explain it to me clearly? thank you.

// My code

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'

Ignore this, above the Alert code below this line, it’s not relevant:

function makeClass() {
  "use strict";
  /* Alter code below this line */

Ignore this, below the Alter code above this line, it’s not relevant:

  /* Alter code above this line */
  return Vegetable;
}
const Vegetable = makeClass();

Just focus on this:

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

You are saying you want to make an object with one property (name), and that you want to specify what that name should be in the function that constructs the object (the constructor).

These two lines are an example of how you would use the class:

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

NOTE the code using class is exactly the same as this code:

function Vegetable(name) {
  this.name = name;
}
1 Like

That was a really helpful and well-written reply. Thank you! … I’m wondering how useful it is to master this lesson. Even after reading your super, well-explained reply, I know that I’m going to forget this tomorrow. Is this something that is used often? It seemed like it could be useful if we could put more properties into the object we’re making, so I tried that:

class Vegetable {
  constructor(name, color, root, perennial) {
    this.name = name;
    this.color = color;
    this.root = root;
    this.perennial = perennial;
    this.binaryFirstLetter = binaryFirstLetter;
  }
}

const carrot = new Vegetable(`carrot`, 'orange', yes, no, 01100011);

console.log(carrot.root);

The strings worked, but the Booleans didn’t. The console says “yes is not defined”. So, it’s looking at the values we are putting in as strings. Other types such as Booleans and numbers don’t seem to work. Is there a way to make that work? If not, is this really something noobs should be spending a lot of time trying to grasp?

They aren’t booleans, booleans are true or false. And the number doesn’t work because you’re missing that parameter from the constructor

class Vegetable {
  constructor(name, color, root, perennial, binaryFirstLetter) {
    this.name = name;
    this.color = color;
    this.root = root;
    this.perennial = perennial;
    this.binaryFirstLetter = binaryFirstLetter;
  }
}


const carrot = new Vegetable(`carrot`, 'orange', true, false, 01100011);

Yes. A class is just a useful way to define a type of data (so you’re creating a Vegetable) with some functions that only work with that type. This is really useful.

The way JavaScript works means that unlike other very popular languages (for example Java or C#), everything does not have to be a class, and in fact you don’t need to use classes at all (in those languages you can’t just have variables or functions just floating around outside a class). But this doesn’t mean they aren’t extremely useful.

Thanks so much for the reply! I’m more confused now, though. In the FCC example, yes, I get it that the value for name isn’t a Boolean. But if we’re creating an object, some of the values of some of the properties could or should be able to be Booleans, right? Or numbers. That’s why I tried creating vegetable object that had a key/value pair of root: yes (Boolean value). And binaryFirstLetter: 01100011. To test it to see if we could create an object that had Boolean or number values. If we can’t then it doesn’t seem like a very useful way to create an object. Now I’m not sure, though, if I misunderstood what we are doing here. Thanks again. I really appreciate your time and effort!

yes is not a Boolean value! A Boolean value is true or false, that’s it. Nothing else, it doesn’t matter if you’re doing maths or programming or philosophy or whatever, it’s always just true or false.

Re your code, as an example:

function example(perennial) {
  return perennial;
}

If I try to run example(yes), thats is a syntax error, because yes is not a thing

You weren’t passing the number as a parameter.

function example() {
  return binaryFirstLetter;
}

If I run example(01101011), that’s not going to work: I haven’t defined the parameter on the original function. It needs to be written (as with every function):

function example(binaryFirstLetter) {
  return binaryFirstLetter;
}

Also, unsure why you’re trying to use binary numbers, but binary literals are written in JS like 0b01101011, what you’re writing is the decimal number 1101011 (edit: or it gets parsed as an octal. I think that behaviour has been stopped in newer browsers, where you have to prefix an octal literal with 0o rather than just 0)

Haha - sorry - I realized when I was going to bed last night that I had put yes instead of true. Der. Brain fart from studying too long. I’m going to experiment some more after my coffee. And thanks for the info about using Booleans. I’ll try that, too. Much appreciated! Have a great day!

1 Like

With my brain refreshed, I re-coded the experiment, and it works great, making the usefulness of class syntax for creating objects apparent. Yay! Thanks again.

class vegetable {
  constructor(name, color, root, perennial, ID, binaryFirstLetter) {
    this.name = name;
    this.color = color;
    this.root = root;
    this.perennial = perennial;
    this.ID = ID;
    this.binaryFirstLetter = binaryFirstLetter;
  }
}

const carrot = new vegetable('carrot', `orange`, true, false, 3426, 01101011);

console.log(carrot.root);

I mucked around a little with the binary property for fun. You’re right. When you use 0b the outcome parses to a decimal. Without 0b it becomes something else (maybe octal - I don’t know enough about that to know, and I don’t need to know right now). My purpose for including a binary was to see if the browser/JS would read it as a decimal or if it would know it was a binary. It seems as though the leading 0 tells it to read it as binary.

Again, much appreciated. If you hadn’t told me that class syntax was useful in the real world, I would have moved on without taking time to comprehend it. :clap:

1 Like