DEV Community

Cover image for Polymorphism in Javascript

Polymorphism in Javascript

Genix on March 23, 2024

Summary: Polymorphism is a fundamental concept in object-oriented programming (OOP) languages, where "poly" refers to many and "morph" s...
Collapse
 
danbars profile image
Dan Bar-Shalom • Edited

I assume that not on purpose, but your example of man and woman polymorphism is somewhat misogynous. The man is a team captain while the woman is a mother and a wife.

Regardless, nice article.
Here's a small function that can help create method overloading based on signature matching

function overload(patterns, defaultFn) {
    return (...args) => {
        for (const pattern of patterns) {
            if (pattern.match(args)) {
                return pattern.fn.apply(this, args)
            }
        }
        return defaultFn.apply(this, args)
    }
}
Enter fullscreen mode Exit fullscreen mode

And this is how you can use it:

const add = overload([{
    match: args => args.length === 1 && typeof args[0] === 'number',
    fn: (x) => x*2
}], (a,b) => a+b)

add(3) // 6
add(3,2) // 5
Enter fullscreen mode Exit fullscreen mode
Collapse
 
m__mdy__m profile image
Genix

I really apologize if you think my article is misogynistic, I didn't mean it that way, but I just gave some examples to better understand polymorphism.

Collapse
 
danbars profile image
Dan Bar-Shalom

I don't get offended personally by things that people say, and I wasn't looking for an apology.
Yet, words have the power to define the reality in which we live.
If women are defined as "mothers" or "wives" it puts them in a certain spot. Even though you didn't mean it that way, those words help fixating this reality. The problem, imho, is not that your example uses those women roles, but the unbalanced examples. You didn't choose "husband" and "father" for the boy, which implies that boys can be students and captains. And yet, for the women, you chose 2 out of 3 examples which defines them as their place in the family and not as what they do.

If this resonates with you, you can just change the example :)

Thread Thread
 
m__mdy__m profile image
Genix

I made it, do you think it's good?

Thread Thread
 
danbars profile image
Dan Bar-Shalom

Awesome! Thanks :)

Collapse
 
efpage profile image
Eckehard

Awsome!

Collapse
 
abidullah786 profile image
ABIDULLAH786

I think the code example for overloading is correct, we know that for overloading the class should have more than one functions either with difference in number of parameters or at least type of each parameters (or sequence).

But as JavaScript is not type strict language so we can not make a function over loading with types difference the only thing we can do is to play with number of parameters. In you cases you have 2 parameters for both add() functions and i think it will always call the 2nd add function no matter either the numbers are integers or strings

Your exam

class Calculator {
  // Method Overloading: Add with two parameters
  add(a, b) {
    return a + b;
  }

  // Method Overloading: Add with string concatenation
  add(str1, str2) {
    return str1 + str2;
  }
}

const calculator = new Calculator();

console.log(calculator.add(2, 3)); // Outputs: 5 (Addition of two numbers)
console.log(calculator.add("Hello", " World"));
Enter fullscreen mode Exit fullscreen mode
Collapse
 
skyjur profile image
Ski • Edited

Yes it's correct. Js doesn't have method overloading. Also method overloading is not polymorphism have no idea why it's even here. Author doesn't really know js well. The mixin example for example is quite a terrible pattern to use and author doesn't mention anything about downsides only "hey you can do this to do multiple inheritance" but actually no you can't unless you want to shoot your self in the foot.

Collapse
 
m__mdy__m profile image
Genix

Can you tell me which part of the article is wrong?
And I have not said anything about polymorphism

Thread Thread
 
skyjur profile image
Ski • Edited

In functional programming languages like JavaScript

JavaScript is not functional programming language. It's been OOP language from it's very inception days and it has always remained such. Many of it's APIs of built-in collections are modifying-in-place and not immutable but in functional language it's necessary that all apis are immutable. It is possible to write functional inspired architecture in JS but that doesn't change the fact that JS is not functional language. The fact that you use a stone to hammer a nail doesn't turn a stone into a hammer it's still a stone.

Compile-time Polymorphism (Method Overloading):
Explanation:
Compile-time polymorphism, or method overloading, occurs when multiple methods in a class have the same name but different parameter lists

Method overloading is not polymorphism. And JavaScript does not have method overloading. You have brought up method overloading several times in javascript and it's not clear why, since JavaScript does not support it, and also, because this has nothing to do with polymorphism.

It really sounds to me here that you wrote half your article with ChatGPT pulling in all the nonsense generated by language models without doing any filtering. More than half what ChatGPT produces is just utter garbage and if you use it as a tool to help your writing then it's your diligence to fix the garbage before putting it into articles.

Also if you made significant use of ChatGPT you should specify it for transparency so that readers are more easily aware that some of it is not your opinion but just language model garbage.

Thread Thread
 
Sloan, the sloth mascot
Comment deleted
 
m__mdy__m profile image
Genix • Edited

I am learning OOP and OOP concepts
You can see the concepts I chose in this repository:
OOP

I sent my article to chatgpt after finishing it and he gave me this offer and I did it without any special filtering. I'm sorry. I will try not to repeat it
And also I got OOP concepts from him, if possible take a look at it to fix its problems.

Collapse
 
efpage profile image
Eckehard • Edited

Object pascal uses overloading also for simple functions. You can implement the same function multiple times with different parameters, the compiler determines the right function by checking number and type of parameters used by the caller.

We can do something similar building a polymorphic function using parameter type checks to implement different behavoir insinde function. If - for some reason - we do not want to change the initial function, we could do something like this (which is a bit awkward):

let say = (x) => { console.log("This is " + x) }

let s1 = say
say = (x) => {
  if (typeof x !== "number") return s1(x)
  console.log("This is Number " + x)
}

let s2 = say
say = (x) => {
  if (typeof x !== "object") return s2(x)
  console.log("This is Object " + JSON.stringify(x))
}

// call polymorph functions
say("Hallo")
say(3)
say({ Test: "TEST" })
Enter fullscreen mode Exit fullscreen mode

running code here

Do you know any better way to achieve this in JS?

Collapse
 
m__mdy__m profile image
Genix • Edited

Yes, there is a better way:

// Define different strategies
const strategies = {
  default: (x) => console.log("This is " + x),
  number: (x) => console.log("This is Number " + x),
  object: (x) => console.log("This is Object " + JSON.stringify(x))
};

// Function implementing the Strategy Pattern
function say(x) {
  let strategy = strategies.default; // Default strategy

  // Check the type of x and assign the appropriate strategy
  if (typeof x === "number") {
    strategy = strategies.number;
  } else if (typeof x === "object") {
    strategy = strategies.object;
  }

  // Execute the chosen strategy
  strategy(x);
}

// Call the polymorphic function
say("Hello");
say(3);
say({ Test: "TEST" });
Enter fullscreen mode Exit fullscreen mode

running code here

Collapse
 
efpage profile image
Eckehard

Beside the lack of a default value I would prefer this version:

// Define different strategies
const strategies = {
  string: (x) => console.log("This is " + x),
  number: (x) => console.log("This is Number " + x),
  object: (x) => console.log("This is Object " + JSON.stringify(x))
};

// Function implementing the Strategy Pattern
function say(x) {
  strategies[typeof x](x);
}

// Call the polymorphic function
say("Hello");
say(3);
say({ Test: "TEST" });
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
m__mdy__m profile image
Genix

It is really a beautiful code

Thread Thread
 
artydev profile image
artydev

Indeed :-)

Collapse
 
cardoprimo profile image
DDKP

"Certainly! Here's an improved example for ad-hoc polymorphism"
At least proof read your AI content lmao

Collapse
 
m__mdy__m profile image
Genix • Edited

thank you for your attention
Yes, it was my mistake, sorry, I fixed it, but it doesn't mean that the content was generated by AI, I used AI to improve my content :))

Collapse
 
alyrik profile image
Kiryl Anokhin

I'm afraid "Compile-time Polymorphism (Method Overloading)" does not apply to JavaScript and the example code doesn't work as expected.

Collapse
 
m__mdy__m profile image
Genix

It doesn't work in js. It is true because js does not support overriding overload methods like other languages ​​(such as Java).
But what do you mean the code doesn't work?

Collapse
 
alyrik profile image
Kiryl Anokhin

I mean that the 2nd method is always called in that example. So this sentence is not true: "The compiler determines the appropriate method to call based on the provided arguments".
Basically, this example just demonstrates how "+" operator works :)

Thread Thread
 
m__mdy__m profile image
Genix

Yes, it's true. It was my mistake :) I corrected it (actually, I removed that part from the article because many people told me it was wrong!)

Collapse
 
rmiah209 profile image
Raheem Miah

Great, insightful article! Helped me understand polymorphism much better, being a student as well.