JavaScript Interview Question #104

What is the prototype in JavaScript?

Closures, Prototypes, Classes & Advanced Functions Mid-Level Intermediate

Quick Interview Answer

JavaScript objects can have an internal link to another object called their prototype. When a property is not found directly on an object, JavaScript can search its prototype and continue through the prototype chain.

Detailed Explanation

JavaScript objects can have an internal link to another object called their prototype. When a property is not found directly on an object, JavaScript can search its prototype and continue through the prototype chain.

Prototypes provide JavaScript's inheritance and shared-behavior mechanism. Methods placed on a constructor's prototype can be shared by all instances instead of creating a separate function object for every instance.

Code Example

function User(name) {
    this.name = name;
}

User.prototype.greet = function () {
    return `Hello ${this.name}`;
};

const user = new User("Asif");

console.log(user.greet());