Constructor confusion ... JS Newbie

In codecademys JS course, a class is defined as an object blueprint, and to call it you must add the constructor function (constructor()):
class Dog {
constructor(name) {
this.name = name;
this.behavior = 0;
}
}
class Dog {
constructor(name) {
this.name = name;
this.behavior = 0;
}
}
To create an instance, you then use the new keyword ...
const halley = new Dog('Halley');
const halley = new Dog('Halley');
But on javascript.info this is the definition of a constructor function:
function User(name) {
this.name = name;
this.isAdmin = false;
}

let user = new User("Jack");
function User(name) {
this.name = name;
this.isAdmin = false;
}

let user = new User("Jack");
... basically the class definition from codecademy, without the specific constructor() syntax ... So what is a constructor function??? Is it required to use the constructor() or not??
18 Replies
Joao
Joao14mo ago
In JavaScript, the class keyword is what's called syntactic sugar, which means it's just a simpler/nicer way to write something that has the same effect. In this case, a constructor function as shown in the javascript.info snippet. That's the original way of writing classes in JavaScript and it's also what really happens under the hood. But since we have the class keyword it's best to use that instead unless you have good reason not to. Just keep in mind that these are two different ways to write the same thing. So a constructor function is a function that gets invoked immediately after a new instance of an object is created. When using class keyword you don't technically have to provide one but of course this means you won't be able to provide arguments to better define or customize the object. For example, this is valid JavaScript, though not very useful:
class Person {
firstName = 'John';
lastName = 'Doe';
}

const person = new Person();

console.log(person);
class Person {
firstName = 'John';
lastName = 'Doe';
}

const person = new Person();

console.log(person);
Å Marlon G
Å Marlon G14mo ago
Hmm ... ok. So trying to understand ... In the codecademy example, the most basic way of writing a class would be to exclude the constructor():
class Dog {
this.name = name;
this.behavior = 0;
}
class Dog {
this.name = name;
this.behavior = 0;
}
And if so, why cant the parenthesis go after Dog, like class Dog(), as it does in the javascript.info example ...
Joao
Joao14mo ago
That's just the syntax of it. class <nameOfClass> { <bodyOfClass> } Be mindful though, no constructor may be the "most basic way" and it is correct but you will rarely not provide one. Normally you want to define what happens when the object is created, and how many arguments it receives, in what order, etc.
Å Marlon G
Å Marlon G14mo ago
So basically – the javascript.info example isn't used in everyday life?
Joao
Joao14mo ago
Exactly, the class keyword was introduced in JavaScript explicitly to replace it. It's also more consistent with how other languages implement object oriented programming. For example in PHP, Python, Java, Ruby... they also use the same format of class <name> <body> Just remember, in reality, under the hood, the code that actually runs in the browser is the one from javacript.info.
Å Marlon G
Å Marlon G14mo ago
So if someone were to use the javascript.info syntax, the only way of knowing that it is a class blueprint is that to call it the new keyword is being used?
Joao
Joao14mo ago
Yes, if you ever see the this keyword in a function it's most likely that. But I've never seen it personally. It's been a while since the class keyword was introduced so it's just the proper way now. Actually just to clarify that, there are many other cases where you would use the this keyword in a function. But if you see it being used to assign properties within a function, that's the tell you are looking for. That, and the new keyword of course.
Å Marlon G
Å Marlon G14mo ago
Ok. Nice ... that helps a lot. So if I could drag you through the mud I'm in for a real life example. Say you wanted a script that created a new web page everytime someone pushed a button (like a blog page in the cms), then the button would run a function that created an object based on a class called "blog post" ...?
Joao
Joao14mo ago
Well I guess a simple example could look like this:
class Post {
constructor(title, body, author, categories) {
this.title = title;
this.body = body;
this.author = author;
this.categories = categories;
}

html() {
return `
<article>
${this.body}
</article>
`;
}
}

const button = document.querySelector('.create-post');

button.addEventListener(() => {
const p1 = new Post('How to write classes in JS', '...', 'Marlon', ['javascript', 'oop']);
});
class Post {
constructor(title, body, author, categories) {
this.title = title;
this.body = body;
this.author = author;
this.categories = categories;
}

html() {
return `
<article>
${this.body}
</article>
`;
}
}

const button = document.querySelector('.create-post');

button.addEventListener(() => {
const p1 = new Post('How to write classes in JS', '...', 'Marlon', ['javascript', 'oop']);
});
You can then have methods like that to actually output it on the browser, for example. That's just an example on how to use classes not how I would implement this.
Å Marlon G
Å Marlon G14mo ago
In this example, and I understand that it is just that, an example, would the button in the cms be the const p1?
Joao
Joao14mo ago
No, p1 is the blog post. The button would be somewhere else and it would invoke new Post(...) somewhere along the callback. Updated example above, though very simplistic. You would need to extract the data from somewhere else.
Å Marlon G
Å Marlon G14mo ago
Yes! That makes sense! ... just copied it all! Thank you so much! My head is less swollen. 🥹
Joao
Joao14mo ago
If you are curious, I asked chatGPT for an example and it looks similar with with more details:
class BlogPost {
constructor(title, body, author, categories) {
this.title = title;
this.body = body;
this.author = author;
this.categories = categories;
}

displayPost() {
console.log(`Title: ${this.title}`);
console.log(`Body: ${this.body}`);
console.log(`Author: ${this.author}`);
console.log(`Categories: ${this.categories}`);
}
}

function generateRandomBlogPost() {
const titles = ["The Importance of Sleep", "How to Stay Motivated", "The Benefits of Meditation"];
const bodies = ["Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium.", "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident."];
const authors = ["John Doe", "Jane Smith", "Bob Johnson"];
const categories = ["Health", "Productivity", "Mental Health"];

const randomTitle = titles[Math.floor(Math.random() * titles.length)];
const randomBody = bodies[Math.floor(Math.random() * bodies.length)];
const randomAuthor = authors[Math.floor(Math.random() * authors.length)];
const randomCategories = [categories[Math.floor(Math.random() * categories.length)]];

return new BlogPost(randomTitle, randomBody, randomAuthor, randomCategories);
}

const button = document.querySelector('button');
button.addEventListener('click', () => {
const randomBlogPost = generateRandomBlogPost();
randomBlogPost.displayPost();
});
class BlogPost {
constructor(title, body, author, categories) {
this.title = title;
this.body = body;
this.author = author;
this.categories = categories;
}

displayPost() {
console.log(`Title: ${this.title}`);
console.log(`Body: ${this.body}`);
console.log(`Author: ${this.author}`);
console.log(`Categories: ${this.categories}`);
}
}

function generateRandomBlogPost() {
const titles = ["The Importance of Sleep", "How to Stay Motivated", "The Benefits of Meditation"];
const bodies = ["Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium.", "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident."];
const authors = ["John Doe", "Jane Smith", "Bob Johnson"];
const categories = ["Health", "Productivity", "Mental Health"];

const randomTitle = titles[Math.floor(Math.random() * titles.length)];
const randomBody = bodies[Math.floor(Math.random() * bodies.length)];
const randomAuthor = authors[Math.floor(Math.random() * authors.length)];
const randomCategories = [categories[Math.floor(Math.random() * categories.length)]];

return new BlogPost(randomTitle, randomBody, randomAuthor, randomCategories);
}

const button = document.querySelector('button');
button.addEventListener('click', () => {
const randomBlogPost = generateRandomBlogPost();
randomBlogPost.displayPost();
});
And the explanation it gave me: In the code above, we first define a BlogPost class with a constructor that accepts a title, body, author, and categories array. We also define a displayPost method that logs the post's details to the console. Next, we define a generateRandomBlogPost function that generates random values for each parameter using predefined arrays. We use the Math.floor and Math.random functions to select a random value from each array. Finally, we add an event listener to a button that, when clicked, generates a random blog post using the generateRandomBlogPost function and displays it using the displayPost method. This code demonstrates how we can create a flexible and reusable BlogPost class that can be easily invoked and customized with random values. --- (me again) What you would have to do, is figure out how to obtain the values from title, author, etc. Those can probably be extracted from the HTML itself, but I asked it to give me random values and it created these examples.
Å Marlon G
Å Marlon G14mo ago
Wow ... that's quite helpful actually! What was you exact prompt?
Joao
Joao14mo ago
"Write a simple example of a blog post class that gets invoked when a button is clicked. The class accepts a title, body, author and categories array. Randomize these parameters." I find it crucial to keep the prompt short and concise, since chatGPT can go wild in its train of thought.
Å Marlon G
Å Marlon G14mo ago
Yes, exactly! That's why I wanted to know what you wrote. Again – thank you so much! This really helped clear my head on classes! 🙌
Joao
Joao14mo ago
By the way, chatGPT may feel awesome and it is in many ways but I think it's best to consider it helpful tool rather than a pool of answers... it can and often does give wrong answers and if you don't know any better you may be introducing bugs in your code without knowing. Personally I try to use it only with things that I already know how to write, but it's either too tedious or don't remember the exact syntax or whatever necessary details. See rule #6 in #📝rules also.
Å Marlon G
Å Marlon G14mo ago
Indeed!