Home > Web Front-end > JS Tutorial > body text

method overloading in javaScript

Linda Hamilton
Release: 2024-10-17 20:45:02
Original
593 people have browsed it

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`
Copy after login

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!`

Copy after login

The above is the detailed content of method overloading in javaScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!