0
0
Javascriptprogramming~5 mins

Constructors in classes in Javascript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a constructor in a JavaScript class?
A constructor is a special method in a class that runs automatically when a new object is created. It sets up the object with initial values.
Click to reveal answer
beginner
How do you define a constructor inside a JavaScript class?
You define it using the keyword <code>constructor()</code> inside the class body. It looks like a regular method but named <code>constructor</code>.
Click to reveal answer
beginner
What happens if you don't write a constructor in a JavaScript class?
If no constructor is written, JavaScript uses a default constructor that does nothing but allows object creation.
Click to reveal answer
beginner
Can a JavaScript class have more than one constructor?
No, a class can only have one constructor method. Trying to add more will cause an error.
Click to reveal answer
beginner
How do you use parameters in a constructor?
You add parameters inside the constructor() parentheses and use them to set properties on the new object.
Click to reveal answer
What keyword is used to define a constructor in a JavaScript class?
Acreate
Binit
Cbuild
Dconstructor
What happens if you create an object from a class without a constructor?
AJavaScript throws an error
BA default constructor runs
CThe object is not created
DYou must add a constructor manually
How many constructors can a JavaScript class have?
AAs many as you want
BTwo
COne
DNone
Where do you put parameters to initialize object properties in a constructor?
AInside the constructor parentheses
BAfter the class keyword
CInside the class but outside the constructor
DIn a separate method
Which of these is a correct constructor syntax in JavaScript?
Aconstructor() { this.name = 'John'; }
Bfunction constructor() { this.name = 'John'; }
Cclass constructor() { this.name = 'John'; }
Dnew constructor() { this.name = 'John'; }
Explain what a constructor does in a JavaScript class and why it is useful.
Think about how you prepare a new object with starting values.
You got /4 concepts.
    Describe how you would add parameters to a constructor and use them to set object properties.
    Consider how you pass information when creating a new object.
    You got /3 concepts.