Using Functions

Function Overloading

🙋 Need help? Ask an expert now!

JavaScript does not support function overloading, which occurs when you create two functions with the same name. Functions with the same name will hide each other so that the function cannot be called. Therefore, function overloading in JavaScript must be so called "faked". You can create functions that make it look like overloading by changing the number of parameters or the data type of the parameter.

With that being said, creating functions with the same name is bad practice and should not be used. Instead, create a function like printText that checks the number of arguments and prints different results depending on the parameters. This way, you don't have to put a value for each parameter and worry about accidentally printing undefined. Either way, the possibility of running into this type of issue is pretty low, so don't worry too much about having to create methods that read the number of arguments.

Edit Me on GitHub!

Application Question

Consider the following code segment:

function printText(name, number, age) {
                if (arguments.length == 1) {
                } else if (arguments.length == 2) {
                  console.log(name + " " + number);
                } else {
                  console.log(name + " " + number + " " + age);
            printText("Bill", 20);

What will the following code segment print to the console?