Object-Oriented Programming (OOP) in JavaScript is based on prototypes rather than classical class-based inheritance. However, with ES6, JavaScript introduced the class
syntax, making OOP more structured. Here are some commonly asked OOP interview questions in JavaScript.
Basic OOP Concepts
What are the four principles of Object-Oriented Programming?
- Encapsulation
- Abstraction
- Inheritance
- Polymorphism
How does JavaScript implement OOP?
- JavaScript uses prototype-based inheritance rather than class-based inheritance. However, ES6 introduced the
class
keyword, which provides syntactic sugar over prototypes.
- JavaScript uses prototype-based inheritance rather than class-based inheritance. However, ES6 introduced the
What is a constructor function in JavaScript?
- A constructor function is a function used to create objects. Example:
- A constructor function is a function used to create objects. Example:
What is the difference between a class and a constructor function?
- A
class
is syntactic sugar over a constructor function. - Example using a class:
- A
Encapsulation & Abstraction
How do you implement encapsulation in JavaScript?
- Encapsulation can be achieved using private properties (
#
prefix in ES6).
- Encapsulation can be achieved using private properties (
What is abstraction in JavaScript?
- Abstraction is hiding implementation details and only exposing essential functionalities.
- Example:
Inheritance
How does inheritance work in JavaScript?
- JavaScript allows inheritance using
extends
andsuper
. - Example:
- JavaScript allows inheritance using
What is the difference between classical and prototypal inheritance?
- Classical inheritance (as in Java, C#) uses classes.
- Prototypal inheritance (used in JavaScript) links objects to prototypes.
Polymorphism
- How does JavaScript support polymorphism?
- JavaScript supports polymorphism by method overriding.
- Example:
Prototype & this
Keyword
What is a prototype in JavaScript?
- A prototype is an object from which other objects inherit properties.
- Example:
What is the difference between
__proto__
andprototype
?prototype
is a property of constructor functions.__proto__
is a property of objects referring to their prototype.
What does the
this
keyword refer to in JavaScript?this
refers to the context in which a function is executed.- Example:
Miscellaneous
What is method overriding?
- Subclass provides a new implementation for an inherited method.
How does JavaScript handle multiple inheritance?
- JavaScript does not support multiple inheritance directly but allows multiple prototypes using mixins.
What is the difference between shallow copy and deep copy in JavaScript?
- Shallow copy: Copies only references (e.g.,
Object.assign
). - Deep copy: Copies all nested properties (e.g.,
JSON.parse(JSON.stringify(obj))
or structured cloning API).
- Shallow copy: Copies only references (e.g.,