What is Prototype in JavaScript?

Description:

Prototypes are a core feature in JavaScript that enables object inheritance. Every object in JavaScript has an internal [[Prototype]] property that links to another object.

Explanation:

JavaScript follows prototypal inheritance, where objects inherit properties and methods from other objects, rather than classes. When a property is accessed on an object, JavaScript first looks for it in the object itself. If not found, it checks the prototype chain.

For example:

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

Person.prototype.greet = function() {
    console.log(`Hello, my name is ${this.name}`);
};

const person1 = new Person("Alice");
person1.greet(); // Output: Hello, my name is Alice

Here, greet() is added to the prototype, so all instances of Person can use it without storing it individually in each object.