A JavaScript
practice question on closures
says the following:
Change the function to support multiple function calls:
function joinWords(a, b) {
return console.log(a + ' ' + b);
}
See example cases below for example inputs and their expected outputs.
Input 1:
const greet = joinWords("Hello");
greet("world);
Output 1:
"Hello World"
Input 2:
const greet = joinWords("Hey", "there!");
greet("Where", "is", "Foo", "Bar?");
Output 2:
"Hey there! Where is Foo Bar?"
For the solution, I've successfully implemented a closure, but I'm still console logging undefined parameters. AKA, for the first test case (Input 1 and Output 1) I'm outputting Hello undefined World undefined undefined undefined. How can I elegantly exclude undefined parameters here?
function joinWords(a, b) {
return function(c, d, e, f) {
console.log(
a + ' ' + b + ' ' + c + ' ' + d + ' ' + e + ' ' + f
);
};
}
You might be looking for rest parameters, which make the function accept any number of arguments and passes them over as an array (which one can then call the .join
method on):
function joinWords(...values) {
return values.join(" ");
}