JS interview in 2 minutes / Polymorphism (OOP)
Tags: javascript, typescript, beginners, career
Published: 2021-04-30 10:37:06

---
title: JS interview in 2 minutes / Polymorphism (OOP)
published: true
description: Let's try to figure out how to answer common JS questions in an interview.
tags: javascript, typescript, beginners, career
cover_image: https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/Unofficial_JavaScript_logo_2.svg/1920px-Unofficial_JavaScript_logo_2.svg.png
---

**Question:**
What is Polymorphism?

**Quick answer:**
It is an ability to use objects of different types, providing them the same interface, or use of one entity representing different types.

**Longer answer:**
As we discussed in [previous article about inheritance](https://dev.to/kozlovzxc/js-interview-in-2-minutes-inheritance-in-oop-53h2), it is possible to move shared functionality to the parent class and then extend it in child classes.

But how do we actually work with this shared functionality? 

We can just expect that we are always working with an instance of the parent class, but they may be instances of the child classes. It may be intuitive, but it is called [subtyping polymorphism](https://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping).

```javascript
class Human {
    sayHi() {
        alert('Hi! ')
    }
}

class Child extends Human {
    sayHi() {
        alert('Hi 👶')
    }
}

class Parent extends Human {
    sayHi() {
        alert('Hi 🙋‍♀️')
    }
}

class GrandParent extends Human {
    sayHi() {
        alert('Hi 👵')
    }
}

// In Typescript:
// function introduce(human: Human) {
function introduce(human) {
    human.sayHi()
}

let childObj = new Child()
introduce(childObj);
let parentObj = new Parent()
introduce(parentObj)
let grandParentObj = new GrandParent()
introduce(grandParentObj)
```

There is also a bit more complex polymorphism example, called [parametric polymorphism](https://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Parametric_polymorphism). It is just generics in Typescript.

```typescript
class <T>List {
  data: T[];
  push(elem: T) {} 
  pop(elem: T) {}
}
```

Since JavaScript is a [dynamically typed language](https://dev.to/kozlovzxc/js-interview-in-2-minutes-static-vs-dynamic-typing-2d5k), I don't think there is such thing as parametric polymorphism, but please correct me if I'm wrong.

The last thing we will touch is [ad hoc polymorphism](https://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Ad_hoc_polymorphism). It is when you have one function name, but different types of arguments. As JavaScript is a dynamically typed language, these checks are performed during runtime.

```javascript
function add(a, b) {
  if (Array.isArray(a) && Array.isArray(b)) {
    return a.concat(b)
  }
  if (typeof a === 'number' && typeof b === 'number') {
    return a + b
  }
  if (typeof a === 'string' && typeof b === 'string') {
    return a + b
  }
  throw new Error('Unknown types')
}

add(1,2) // 3
add('abc', 'def') // 'abcdef'
add([1,2], [3,4]) // [1, 2, 3, 4]
```

**Real-life applications:**

Basically, the use of polymorphism can open Pandora's box to the world of utils & helpers which only their creator knows how to use.

![](https://mk0knowtechiec1j578p.kinstacdn.com/wp-content/uploads/2019/07/galaxy-brain-meme-1000x600.jpg)

^^^ That feeling when you understood a few hundreds of lines of code, which checks all cases for all types in one place 🤯

Another caveat is to extend parent class in a way that it is no longer replaceable.

```javascript
class Bird {
  fly() {}
}

class Pigeon extends Bird { }

class Penguin extends Bird {
  fly() { throw new Error("I can't fly!") }
}

function makeThemFly(birds) {
  birds.forEach(bird => bird.fly())
}

makeThemFly([new Pigeon(), new Penguin()]) // This will blow 💥
```

**Resources:**
[wiki/Polymorphism](https://en.wikipedia.org/wiki/Polymorphism_(computer_science))
[w3schools/Polymorphism (Java)](https://www.w3schools.com/java/java_polymorphism.asp)
[MDN](https://developer.mozilla.org/en-US/)

**Other posts:**
* [JS interview in 2 minutes / Inheritance in OOP](https://dev.to/kozlovzxc/js-interview-in-2-minutes-inheritance-in-oop-53h2)
* [JS interview in 2 minutes / Object-Oriented Programming (OOP)](https://dev.to/kozlovzxc/js-interview-in-2-minutes-object-oriented-programming-oop-3443)
* [JS interview in 2 minutes / Static vs Dynamic typing](https://dev.to/kozlovzxc/js-interview-in-2-minutes-static-vs-dynamic-typing-2d5k)

---

Btw, I will post more fun stuff here and on [Twitter](https://twitter.com/kozlovzxc). Let's be friends 👋