Simple Javascript Quiz

Short explanation to a moderate level Javascript brainteaser

Question

Which of the following JavaScript snippets will create an alert box containing “Hello John Doe”?

Option 1)

var Person = function (firstName, lastName, age) {
this.firstName = firstName,
this.lastName = lastName,
this.age = age;
};
person = new Person(“John”, “Doe”, “50”)
Person.prototype.sayHello = function () {
alert(“Hello “ + this.firstName + “ “ + this.lastName);
}
person.sayHello();

Option 2)

var Person = function (firstName, lastName, age) {
this.firstName = firstName,
this.lastName = lastName,
this.age = age;
};
person = new Person(“John”, “Doe”, “50”)
Person.sayHello = function () {
alert(“Hello “ + this.firstName + “ “ + this.lastName);
}
person.sayHello();

Option 3)

var person = {
firstName: “John”,
lastNAme: “Doe”,
age: “50”
}
person.sayHello = function () {
alert(“Hello “ + this.firstName + “ “ + this.lastName);
}
person.sayHello();

Option 4)

var person = {
firstName: “John”,
lastNAme: “Doe”,
age: “50”
}
person.prototype.sayHello = function () {
alert(“Hello “ + this.firstName + “ “ + this.lastName);
}
person.sayHello();

Answer

Both 1 and 3 are correct, while 2 and 4 return errors.

Option 2 returns an error because the function declaration fails to instantiate with a “.prototype” call, creating a method that doesn’t carry over to new instances.

Option 4 returns an error because the function declaration includes the “.prototype” call, but makes it unnecessary as the original object was called without proper constructor.