Challenge - 5 Problems
Constructor Functions Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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.');
Attempts:
2 left
💡 Hint
Remember that the new keyword creates a new object and sets this inside the function.
✗ Incorrect
The constructor function assigns name and age to the new object. So p.name is 'Alice' and p.age is 30.
❓ Predict Output
intermediate2: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);
Attempts:
2 left
💡 Hint
Without new, the function does not return an object unless explicitly returned.
✗ Incorrect
Calling Car without new runs the function but does not create or return an object. So c is undefined.
❓ Predict Output
advanced2: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());
Attempts:
2 left
💡 Hint
Prototype methods are shared by all instances.
✗ Incorrect
The speak method uses this.type which is 'Dog' for the dog instance.
🧠 Conceptual
advanced2: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');
Attempts:
2 left
💡 Hint
If a constructor returns an object explicitly, that object is used instead of this.
✗ Incorrect
Returning an object from a constructor replaces the created object, so obj is the returned object.
🔧 Debug
expert2: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());
Attempts:
2 left
💡 Hint
Arrow functions do not have their own this; they use the surrounding context.
✗ Incorrect
The arrow function uses the outer this, which is not the User instance, so this.name is undefined.