"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > method overloading in javaScript

method overloading in javaScript

Published on 2024-11-08
Browse:570

method overloading in javaScript

JavaScript, method overloading (like in languages such as Java or C#) isn’t directly supported because functions can only have one definition. However, JavaScript being dynamic allows us to mimic overloading using techniques like:

Checking arguments count or types.
Using default parameters.
Using arguments or rest parameters.
Below are some ways to implement overloading behavior.

1. Using arguments Object

`function add() {
  if (arguments.length === 1) {
    return arguments[0];  // Single argument
  } else if (arguments.length === 2) {
    return arguments[0]   arguments[1];  // Two arguments
  }
}
console.log(add(5));       // 5
console.log(add(5, 10));   // 15`

arguments is an array-like object that holds all the parameters passed to the function.
Based on the number of arguments, we perform different logic.

2. Overloading with Type Checks

`function greet(name) {
  if (typeof name === "string") {
    console.log(`Hello, ${name}!`);
  } else if (Array.isArray(name)) {
    console.log(`Hello, ${name.join(", ")}!`);
  }
}

greet("Alice");           // Hello, Alice!
greet(["Alice", "Bob"]);  // Hello, Alice, Bob!`

Release Statement This article is reproduced at: https://dev.to/munna_thakur_2019444f0351/method-overloading-in-javascript-1dg2?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3