What is done in javascript in this regard is to create a function and, at the beginning of the implementation of the function, analyze and treat the arguments so that it can be used in a more dynamic way. By setting a function twice javascript overwrites the first implementation of the function, you have no immutability.
A function that would translate the functionality you search, written in javascript, would be the following:
function teste() {
if(arguments.length === 0)
return "hello world"
if(arguments.length === 1 &&
typeof(arguments[0]) === 'string')
return arguments[0];
if(arguments.length === 2 &&
typeof(arguments[0]) === 'string' &&
typeof(arguments[1]) === 'string')
return arguments[0] + arguments[1];
}
// Para casos tratados
teste(); // "hello world"
teste("teste1"); // "teste1"
teste("teste1", "teste2"); // "teste1teste2"
// Para casos não tratados
// Quando uma função não retorna, explicitamente, nenhum valor, você recebe undefined
teste("teste1", "teste2", "teste3"); // undefined
teste(1); // undefined
teste("teste1", 1); // undefined
Within the scope of every function you can access the variable arguments
. This variable represents an object whose indices are numbers, starting at zero. I believe this is the key to solving your problem.
Ex.:
// arguments = {length: 0}
teste();
// arguments = {length: 1, 0: "teste1"}
teste("teste1");
// arguments = {length: 2, 0: "teste1", 1: "teste2"}
teste("teste1", "teste2");
// arguments = {length: 3, 0: "teste1", 1: "teste2", 2: "teste3"}
teste("teste1", "teste2", "teste3");
// arguments = {length: 1, 0: 1}
teste(1);
teste("teste1", 1); // arguments = {length: 2, 0: "teste1", 1: 1}
From the accepted answer it was clear that the intention of the question is the same as the existing question, so I voted to close as duplicate.
– Maniero