Javascript Function Overloading

Introduction

Javascript functions cannot be overloaded in the traditional way.

The functions in Javascript don't have signatures.

The arguments are represented as an array containing zero or more values.

Without function signatures, true overloading is not possible.

If two functions are defined with the same name in Javascript, the last function becomes the owner.

function addSomeNumber(num) {
    return num + 100;
}

function addSomeNumber(num) {
    return num + 200;
}

let result = addSomeNumber(100); // 300 

The previous example is almost equivalent to the following:

let addSomeNumber = function(num) {
    return num + 100;
};

addSomeNumber = function(num) {
    return num + 200;
};

let result = addSomeNumber(100); // 300 

We can simulate overloading of methods by checking the type and number of arguments passed into a function.




PreviousNext

Related