FAQ: Classes - Constructor

This community-built FAQ covers the “Constructor” exercise from the lesson “Classes”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Introduction To JavaScript
Learn Intermediate JavaScript

FAQs on the exercise Constructor

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

why semicolon( ; ) when writing a constructor method to define key and properties of class why not a comma(,) in between two properties like normally when we define properties of an object.

class Surgeon {
constructor(name,department){
this._name=name;
this._department=department;
}
}

9 Likes

I think beacause, it is not a javascript object that separates its properties with comma. The constructor acts like a function so everyline could be an independent statement or line of code. If you want you can remove the semicolon.

2 Likes

Inside the Surgeon constructor() , create name and department properties and set them equal to your input parameters.
I there any difference between
constructor(inputOne, inputTwo) {
this.inputOne = inputOne;
this.inputTwo = inputTwo; }
OR
constructor(inputOne, inputTwo) {
this._inputOne = inputOne;
this._inputTwo = inputTwo;}

1 Like

“By convention, we capitalize and CamelCase class names.”

Isn’t it just a PascalCase? (https://pl.wikipedia.org/wiki/PascalCase)

4 Likes

Yes, I saw that too. I think they mean PascalCase rather than camelCase.

2 Likes

Hi, i wonder why a constructor method is necessary in a class. I mean why don’t we simply add attributes like we would with any other object? Or even variables ?
Best

In classes we always have a constuctor. Constructor is a speacial function that is used for object initialization. Even if you don’t define a constructor, then there will be a default constructor defined automatically.

Your class can have only one constructor. If you try to add more that one constructor, it will throw a syntax error.

A constructor element is necessary. I think that the constructor “function”, it “constructs” a new object, so you don’t have to type duplicate lines of code.

The constructor method is how we are able to pass in unique property values for each new instance. Without a constructor all we can do is instantiate identical objects.

class Foo {
    foobar (arg) {
        return `Foo${arg}`
    }
}

foo = new Foo()

console.log(foo.foobar('bar'))
// "Foobar"

Note how even though there is no constructor we are still able to create a new instance. All it has is one method, though.

This goes a little beyond what the lessons teach, so far, but it can’t hurt to have a sneak peek…

Class also has a prototype so we can extend it with,

Foo.prototype.random = function(ubound) { return Math.floor(Math.random() * ubound + 1)}

Even if we have some instances already in play, they will not need to be recreated. The new method will be accessible to those instances…

foo.random(10)
// 3
foo.random(100)
// 90

We can inspect our class definition and its prototype…

Foo.toString()
/*
"class Foo {
    foobar (arg) {
        return `Foo${arg}`
    }
}"
*/
Foo.prototype.random.toString()
// "function(ubound) { return Math.floor(Math.random() * ubound + 1)}"

8 posts were split to a new topic: “The behavior property is always initialized to zero.”

I think from a previous lesson they mentioned we should use _ when telling other developers looking at our code that they shouldn’t change these key names.

class Surgeon {
  constructor(name, department) {
    this.name = name;
    this.department = department;
  }
}

Just to be sure to well understand :slight_smile:

In the example

class Surgeon {
constructor(name, department){
this.name = name;
this.department = department;
}
}

What are the objects of the class Surgeon ?

Is name and department are properties or objects?

Is there objects inside the class or the two must be distinguish ?

And when we say we create new instance thanks to constructor , does it mean we create new properties or new objects? I have some difficulty to well understand the instance meaning here.

const surgeonCurry = new Surgeon (“Curry”, “Cardiovascular”); //surgeonCurry is the object right?

const surgeonDurant = new Surgeon (“Durant”, “Orthopedics”);

They are properties, but their respective values are objects. The class definition is also an object, as are all instances of that class given the blueprint of the class.

Consider,

console.log(typeof surgeonCurry)    //  object

console.log(typeof surgeonCurry.name)    //  string

console.log(typeof surgeonCurry.department)    //  string

We know that strings are also objects.

console.log(typeof Surgeon)    //  function

We know that functions are also objects.

1 Like

I have the same question as one of the posts above that I would like to confirm:
The question- When we write with the constructor() method,

The answer, as to how I understand it: The constructor() method is not a JavaScript object, and therefore does not need to separate its key-value pairs with commas. Instead, the constructor() method behaves like (but is not) a function, and it is good practice to use semi-colons after each line of code in a function.

I hope this can help anyone who will be looking at these posts later on. If something is off with the explanation above, please let me know! I’d really like to understand.

Another similar question arose- because of the same reason above, is this why we use the “=” sign instead of ":"s?
(for instance, in the following code)

this._name=name;
this._department=department;

Thank you in advance for the help!

Consider the following…

class Foo {
  constructor (a, b) {
    this.a = a;
    this.b = b
  }
}
console.log(typeof Foo.constructor)

Output

function

It is because the constructor is a function that statements are used, not key-value pairs.

The way you put that makes so much sense! So then, just to confirm, constructors are methods which also belong to the functions category?

Thank you for your help and the clarification!

Methods are first and foremost functions. We only access them differently. Let’s expand on the earlier example above…

class Foo {
  constructor (a, b) {
    this.a = a;
    this.b = b
  }
  foo () {
    return this.a > this.b && this.a || this.b > this.a && this.b || 'Equal'
  }
}
console.log(new Foo(7, 6).foo(), new Foo(5, 6).foo(), new Foo(6, 6).foo())
7 6 'Equal'
const foo = (u, v) => u > v && u || v > u && v || 'Equal'
console.log(foo(7, 6), foo(5, 6), foo(6, 6))
7 6 'Equal'

Notice how both the method and the function behave exactly the same way, but have a different execution context? That is all that separates the two. They are both function objects.

Ohh yes that’s right! Thank you so much for the help. :+1: I think I got it now!

1 Like