0
0
Javascriptprogramming~20 mins

Constructor functions in Javascript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Constructor Functions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple constructor function
What is the output of the following code?
Javascript
function Person(name, age) {
  this.name = name;
  this.age = age;
}

const p = new Person('Alice', 30);
console.log(p.name + ' is ' + p.age + ' years old.');
ATypeError
B"Alice is 30 years old."
C"Alice is undefined years old."
D"undefined is 30 years old."
Attempts:
2 left
💡 Hint
Remember that the new keyword creates a new object and sets this inside the function.
Predict Output
intermediate
2:00remaining
Effect of missing new keyword
What happens when you call a constructor function without the new keyword?
Javascript
function Car(make, model) {
  this.make = make;
  this.model = model;
}

const c = Car('Toyota', 'Corolla');
console.log(c);
Aundefined
BAn object with make and model properties
CTypeError
DReferenceError
Attempts:
2 left
💡 Hint
Without new, the function does not return an object unless explicitly returned.
Predict Output
advanced
2:00remaining
Prototype method behavior
What is the output of this code?
Javascript
function Animal(type) {
  this.type = type;
}
Animal.prototype.speak = function() {
  return this.type + ' makes a sound';
};
const dog = new Animal('Dog');
console.log(dog.speak());
ATypeError
B"undefined makes a sound"
C"Dog makes a sound"
D"Animal makes a sound"
Attempts:
2 left
💡 Hint
Prototype methods are shared by all instances.
🧠 Conceptual
advanced
2:00remaining
Understanding constructor return values
What will be the value of obj after running this code?
Javascript
function Gadget(name) {
  this.name = name;
  return { name: 'Override' };
}
const obj = new Gadget('Original');
A{ name: 'Original' }
BTypeError
Cundefined
D{ name: 'Override' }
Attempts:
2 left
💡 Hint
If a constructor returns an object explicitly, that object is used instead of this.
🔧 Debug
expert
2:00remaining
Fixing prototype method context error
What error will this code produce when calling greet, and why?
Javascript
function User(name) {
  this.name = name;
}
User.prototype.greet = () => {
  return 'Hello, ' + this.name;
};
const u = new User('Sam');
console.log(u.greet());
A"Hello, undefined"
BReferenceError
CTypeError
D"Hello, Sam"
Attempts:
2 left
💡 Hint
Arrow functions do not have their own this; they use the surrounding context.