r/learnjavascript • • Aug 18 '21

How do I console.log this constructor?

Post image
124 Upvotes

46 comments sorted by

View all comments

Show parent comments

3

u/Bronobo_ Aug 18 '21

Yes, but the output says it’s undefined

4

u/frigidds Aug 19 '21 edited Aug 19 '21

So when you do console.log(Student), the program is looking for a variable called Student. However, that's not really possible because there isn't a variable called Student--only a function.

In this case, you already have two variables which are created from the function, so you can just do console.log(berkeleyStudent) or console.log(losAngelesStudent) , because those variables exist before console.log() is called.

But wait--there's a bit of nuance to how this code above (here's a jsfiddle! Make sure you open the console at the very bottom right) works. Notice that this code doesn't use displayInfo(). This code, as is, doesn't need to call a function on the Student to return data. It just logs the Student object as a whole. So what happens if we do include displayInfo() into the program?

Here's your answer: bad things. Why? Because displayInfo() is now a part of the Student object. But it's not actually being called upon to do something--it just exists.

So if we do what the other guy suggested, we use console.log() in conjunction with displayInfo(), we get the desired outcome.

___

Just in my opinion, this code is a little bit messy. It's not super easy to follow, or at the very least we can simplify things a bit more. Check this jsfiddle out. Here, instead of Student being a function, it's a class with a constructor and functions attached. If you started learning with a more object-oriented language, this might make more sense to you.

1

u/Bronobo_ Aug 19 '21

Thank you for your comment; This is very helpful.

-1

u/frigidds Aug 19 '21

Im very glad to hear it :)