0
0
Javascriptprogramming~20 mins

Constructors in classes in Javascript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Constructor Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What 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');
AHello, Alice!
Bundefined
CHello, undefined!
DTypeError
Attempts:
2 left
💡 Hint
Look at what the constructor does with the name parameter and the console.log statement.
Predict Output
intermediate
2:00remaining
What 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);
ANaN
B4
Cundefined
D5
Attempts:
2 left
💡 Hint
The constructor adds 1 to the age parameter before assigning.
Predict Output
advanced
2:00remaining
What 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();
ANo error
BTypeError
CSyntaxError
DReferenceError
Attempts:
2 left
💡 Hint
Check the syntax of the constructor declaration.
Predict Output
advanced
2:00remaining
What 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();
ACount is 0\nCount is 1
BCount is 1\nCount is 2
CCount is 1\nCount is 1
Dundefined\nundefined
Attempts:
2 left
💡 Hint
Look at how the static property Counter.count is used and updated.
🧠 Conceptual
expert
2:00remaining
Which 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?
Aclass B { constructor(x) { this.x = x.toString(); } } const b = new B();
Bclass A { constructor() { this.x = 1; } } const a = new A();
Cclass C { constructor() { return {}; } } const c = new C();
Dclass D { constructor() { this.x = 1; return 5; } } const d = new D();
Attempts:
2 left
💡 Hint
Consider what happens if you call a constructor that expects a parameter but you don't provide one.