loading...

Creating objects using the "class" keyword

zmiles17 profile image zmiles17 ・2 min read

This past week in my coding bootcamp, I learned how to make objects using the "class" and "constructor" keywords. Using this method, creating new objects becomes simpler and makes our code much cleaner. To demonstrate, here is what creating objects would look like if we did not have the "class" and "constructor" keywords.

In my demonstration, I have created all of the objects within the students array manually by copying the previous object and replacing the values. I hope you can understand that this can become tedious, especially if I was creating an object for every student in the school. Here is the same output using the aforementioned "class" and "constructor" keywords:

Initially, we can see that the lines of code have been reduced. I don't have to copy and paste the same object over and over. As long as I know how I constructed my class object, I can use the "new" keyword to create a new object easily and quickly. Another thing to note is that class declarations are not hoisted. If I tried to create a new student before the "class Student" is declared, then it would throw an error.

Another cool thing about JavaScript classes is that we can attach methods specific to each object.

Now each student has a method called "enroll()", which will change the value of active to true if it is currently false. If active is already true, then nothing changes. Classes are particularly useful to avoid redundancies and for easily editing object values. Thanks for reading!

Posted on by:

Discussion

markdown guide
 

I wish you luck in your JavaScript journey! It will be one hell of a ride for sure.

When you're done with your bootcamp, I highly recommend that you learn what works under the hood when you use classes in JavaScript. I specifically mean Constructor Functions and the Prototype Chain. These are not essential topics to learn in JavaScript nowadays since we have "classes", but it never hurts to learn more about the language, right? So yeah, learn these concepts when you have time after your bootcamp.

Keep up the learning, my friend! Never give up.