ZL
About Articles Contact
Published on Jul 22, 2020
Filed under:
#javascript

Polymorphism in JavaScript

For the longest time, I thought that “Polymorphing” was about converting something into sheep (thanks to Warcraft). The sheep image stuck with me and made it hard to understand exactly what Polymorphism is.

Today I want to explore what Polymorphism actually is. (Fun fact: Most articles about Polymorphism in JavaScript covers less than 1/3 of what it actually is).

What is Polymorphism

Polymorphism comes from the word Polymorph.

  • Poly: Many.
  • Morph: Change from one form to another.

So Polymorphism is the ability to take on multiple forms.

**There are three kinds of Polymorphism in programming: **

  1. Adhoc Polymorphism
  2. Parametric Polymorphism
  3. Subtype Polymorphism

Most articles on Object Oriented Programming and Polymorphism explains the 3rd type only. They don’t explain the other two.

Adhoc polymorphism

Adhoc is used to describe creation of something without previous planning. In other words, Adhoc Polymorphism means to change something from one form to another on the spot.

There are many forms of Adhoc Polymorphism

  1. Operator Overloading
  2. Function Overloading
  3. Coercion Polymorphism

Operator Overloading

Overloading means being able to do more than one thing.

Example:

The + operator in JavaScript does many things. You can use it to add numbers. You can also use it to concatenate strings.

// Adding numbers
1 + 1 // Results in 2
// Adding Strings
'Hello' + ' ' + 'World' // Results in 'Hello World'
// Adding Numbers to Strings
1 + 'up' // Results in '1up'