Challenge - 5 Problems
Constructor Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this class constructor code?
Consider the following JavaScript class with a constructor. What will be printed when creating a new instance?
Javascript
class Person { constructor(name) { this.name = name; console.log(`Hello, ${this.name}!`); } } const p = new Person('Alice');
Attempts:
2 left
💡 Hint
Look at what the constructor does with the name parameter and the console.log statement.
✗ Incorrect
The constructor receives 'Alice' as the name argument, assigns it to this.name, and then logs 'Hello, Alice!'.
❓ Predict Output
intermediateWhat will be the value of the property after creating an instance?
Look at this class and what happens when we create an instance. What is the value of obj.age?
Javascript
class Animal { constructor(age) { this.age = age + 1; } } const obj = new Animal(4);
Attempts:
2 left
💡 Hint
The constructor adds 1 to the age parameter before assigning.
✗ Incorrect
The constructor adds 1 to the input age (4), so this.age becomes 5.
❓ Predict Output
advancedWhat error does this class code produce?
This class tries to use a constructor but has a mistake. What error will happen when running this code?
Javascript
class Car { constructor() { this.brand = 'Toyota'; } } const myCar = new Car();
Attempts:
2 left
💡 Hint
Check the syntax of the constructor declaration.
✗ Incorrect
The constructor is missing parentheses '()' after the word constructor, causing a SyntaxError.
❓ Predict Output
advancedWhat is the output of this class with multiple constructor calls?
What will be printed when creating two instances of this class?
Javascript
class Counter { constructor() { if (!Counter.count) { Counter.count = 0; } Counter.count++; console.log(`Count is ${Counter.count}`); } } new Counter(); new Counter();
Attempts:
2 left
💡 Hint
Look at how the static property Counter.count is used and updated.
✗ Incorrect
Counter.count starts undefined, so first instance sets it to 0 then increments to 1. Second instance increments to 2.
🧠 Conceptual
expertWhich option will cause an error when creating an instance?
Given these class definitions, which one will cause an error when you try to create a new instance?
Attempts:
2 left
💡 Hint
Consider what happens if you call a constructor that expects a parameter but you don't provide one.
✗ Incorrect
Option A causes a TypeError because no argument is passed, so x is undefined, and undefined.toString() throws "Cannot read properties of undefined (reading 'toString')". Option A has no required parameter. Option A returns an object (allowed, overrides 'this'). Option A returns a primitive (ignored).
