In JavaScript, everything is an object, including functions, arrays, and strings, which are specialized types of objects. JavaScript follows a prototype-based system, where objects inherit properties and methods from other objects through prototypes. This prototype mechanism plays a key role in how JavaScript handles inheritance and object relationships.
What is Prototype in JavaScript?
In JavaScript, the prototype is a container for methods and properties. When methods or properties are added to the prototype of a function, array, or string, they become shared by all instances of that particular object type. Prototype in general can be understood as a mould and all its instances can be considered as the car made from it.
JavaScript
Object.prototype.print = function () {
console.log('I am from object prototype')
}
let b = {
name: 'Pranjal',
age: 21
}
b.print()
OutputI am from object prototype
- Every JavaScript object has a prototype, which contains shared methods and properties that all instances of that object can use. It's like a template for objects.
- When you add a method or property to an object’s prototype, all instances of that object automatically have access to it.
- In this example, the print() method is added to Object.prototype, so any object (like b) can use it.
- Using prototypes helps you avoid repeating code. Instead of defining the same methods for each object, you define them once in the prototype, and all objects can use them. This makes your code more efficient.
How Prototype Works in JavaScript?
- In JavaScript, each object has an internal [[Prototype]] property, which points to another object. This allows the object to inherit properties and methods from its prototype.
- When you access a property or method on an object, JavaScript first checks the object itself. If it's not found, it looks in the object's prototype and continues up the prototype chain until it either finds the property or reaches null.
- Functions in JavaScript have a prototype property. This is where you add properties or methods that you want to be available to all instances of objects created by that constructor function.
- Objects created using a constructor function inherit properties and methods from the constructor's prototype. This allows for reusable code and shared behaviour across multiple objects.
- You can add new properties or methods to an object's prototype, and all instances of that object will automatically have access to the new functionality. This is a common way to extend built-in objects like Array or Object.
Creating Constructor Functions
A constructor function in JavaScript is a special function used to create and initialize objects, typically using the new keyword. It sets up properties and methods on the newly created object, allowing for the creation of multiple instances with shared behavior.
JavaScript
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function () {
console.log(`Hello, my name is ${this.name}.`);
};
const n = new Person("Sheema");
n.sayHello();
OutputHello, my name is Sheema.
- A constructor function is a special function used to create and initialize new objects. In this case, Person is a constructor that takes a name argument and assigns it to the name property of the new object using this.
- The sayHello method is added to the Person prototype, meaning all instances of Person will have access to this method, allowing them to say "Hello" with their name.
- The expression new Person("Sheema") creates a new object using the Person constructor, passing "Sheema" as the name argument. The new object is stored in the name variable.
- The sayHello() method is then called on the name object, which outputs "Hello, my name is Sheema." to the console.
Adding method to prototype
This code defines a sum method on the Array.prototype to calculate the sum of all elements in an array. It then calls this method on two different arrays, arr and arr2, and logs the results.
JavaScript
let a1 = [1, 2, 3, 4, 5]
let a2 = [5, 6, 7, 8, 9]
Array.prototype.sum = function () {
let sum = 0
for (let i = 0; i < this.length; i++) {
sum += this[i]
}
return sum
}
console.log(a1.sum())
console.log(a2.sum())
- The sum method is added to Array.prototype, so it can be used by any array to calculate the sum of its elements.
- Inside the sum method, this refers to the array the method is called on, allowing it to loop through and sum its elements.
- The sum() method is called on both a1 and a2, and it correctly computes and logs the sum for each array (15 for a1 and 35 for a2).
Prototype Inheritance
This code demonstrates prototype inheritance where the child constructor inherits from the parent constructor, allowing instances of child to access methods defined in parent's prototype. It also adds a custom caste method in the child prototype.
JavaScript
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function () {
console.log(`${this.name} makes a noise.`);
};
function Dog(name) {
Animal.call(this, name); // Call the parent constructor
}
Dog.prototype = Object.create(Animal.prototype); // Set up inheritance
Dog.prototype.constructor = Dog;
Dog.prototype.speak = function () {
console.log(`${this.name} barks.`);
};
const dog = new Dog('Rex');
dog.speak(); // Rex barks.
- Animal is the parent class with a method speak.
- Dog is the child class, which inherits from Animal and overrides the speak method.
- Object.create(Animal.prototype) sets up the inheritance chain so that Dog objects can access Animal's methods.
Advanced Prototype Use Cases
1. Extending Built-in Objects
In JavaScript, you can extend built-in objects like Array, String, etc., by adding custom methods to their prototypes. This allows you to add new functionality to these objects without modifying the original class.
JavaScript
Array.prototype.first = function () {
return this[0];
};
const n = [10, 20, 30, 40];
console.log(n.first());
- The first method is added to Array.prototype, which allows every array in JavaScript to use this method.
- The first method returns the first element of the array (this[0]), providing a simple utility for arrays.
- After extending the prototype, we create an array numbers and call the first() method, which correctly returns the first element of the array (10).
- This approach does not modify the original Array class itself but adds functionality in a non-intrusive way, ensuring compatibility with other code and future updates.
2. Shared Methods for Performance Optimization
To optimize performance in JavaScript, shared methods are added to prototypes, allowing multiple instances of objects to access the same method without duplicating it for each instance. This reduces memory usage and improves efficiency.
JavaScript
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.introduce = function () {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
};
const person1 = new Person('Pranjal', 25);
const person2 = new Person('Ayaan', 30);
console.log(person1.introduce());
console.log(person2.introduce());
OutputHello, my name is Pranjal and I am 25 years old.
Hello, my name is Ayaan and I am 30 years old.
- The introduce method is added to the Person.prototype, meaning it's shared across all instances of Person, saving memory by not duplicating the method.
- By using prototypes, the introduce method is stored only once, even though it's accessible by all Person instances. This optimizes memory usage.
- Both person1 and person2 can access the same introduce method without each instance having its own copy, improving efficiency.
- The method is part of the prototype chain, which allows it to be inherited by all instances of Person, ensuring that all objects of that type share the same functionality.
3. Dynamic Method Assignment
In JavaScript, dynamic method assignment allows you to add or modify methods on objects or prototypes at runtime. This provides flexibility, enabling you to change or extend functionality dynamically as the program runs.
JavaScript
function Person(name, age) {
this.name = name;
this.age = age;
}
const person1 = new Person('Pranshi', 25);
person1.introduce = function () {
return `Hi, I am ${this.name} and I am ${this.age} years old.`;
};
console.log(person1.introduce());
OutputHi, I am Pranshi and I am 25 years old.
- The introduce method is added dynamically to the person1 object, allowing you to modify or extend the functionality of the object after it's created.
- This flexibility lets you change or add methods to individual objects without modifying the entire constructor or class, enabling runtime customization.
- The dynamically added introduce method only exists on person1, not on other instances of Person, allowing for instance-specific behavior.
- Since the method is added directly to person1, it's not part of the Person prototype, so other instances of Person will not inherit it unless it's added to them individually.
Advantages of Prototypes
- Memory Efficiency: Methods are shared across all instances, reducing memory usage since they're not duplicated for each object.
- Inheritance Support: Prototypes enable inheritance, allowing objects to inherit properties and methods from other objects.
- Flexibility: Methods and properties can be added or modified dynamically at runtime, offering flexibility in extending functionality.
- Performance Optimization: By sharing methods across instances, prototypes help optimize performance, especially for large numbers of objects.
- Code Reusability: Prototypes allow common functionality to be reused across objects, promoting cleaner and more maintainable code.
Prototype chain in JavaScript
In JavaScript, functions, arrays, and strings are all considered types of objects. They are just specialized forms of the general object type. The Object type acts as the parent or base for these different object types. All the other object type's like array's, functions and Strings are connected as a child to the Object through prototype.
JavaScript
let o = {
name: "Pranjal",
age: 21
}
let a = [1, 2, 3, 4, 5]
let s = "Hello GFG"
function p() {
console.log('My name is xyzabc')
}
Object.prototype.common = function () {
console.log('I am a shared method from prototype')
}
o.common()
a.common()
s.common()
p.common()
OutputI am a shared method from prototype
I am a shared method from prototype
I am a shared method from prototype
I am a shared method from prototype
- In this code we are able to see that the method named common is added to the top level hierarchy for the function's , Array's and String's which are finally converted to object's at the runtime .
- Each and Every thing in JavaScript is converted into an Object at run time, that's why as soon as I added the method to the Object's prototype it became accessible to all the other hierarchical children to the Object which are function's, Array's and String's.
- This complete hierarchical structure which contain's the Object as the parent and the function's, Array's and String's as the children of it is called as the Prototype Chain.

To understand more follow the article on prototype chain
Conclusion
JavaScript prototypes are key to inheritance, code reuse, and memory efficiency. They allow methods to be shared across instances, reducing redundancy and improving performance. Prototypes provide flexibility to extend or modify objects dynamically. Understanding them is essential for mastering JavaScript and creating efficient, maintainable applications.
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read
Introduction of Firewall in Computer Network A firewall is a network security device either hardware or software-based which monitors all incoming and outgoing traffic and based on a defined set of security rules it accepts, rejects, or drops that specific traffic. It acts like a security guard that helps keep your digital world safe from unwa
10 min read