I was trying to do the challenge with this code
function addTogether(...args) {
if(args.some(x => typeof(x) !== 'number')){
return undefined;
}
if (args[1] === undefined) {
return (args[1]) => addTogether(args[0], args[1]);
}
return args[0] + args[1];
}
console.log(addTogether(5)(7));
Which did not work. After checking the solution I saw that this works
function addTogether(...args) {
const [first, second] = [...args];
if(args.some(x => typeof(x) !== 'number')){
return undefined;
}
if (second === undefined) {
return (second) => addTogether(first, second);
}
return first + second;
}
console.log(addTogether(5)(7));
Why cant I pass args[1]
as an argument to the second function ?
Thanks
sanity
September 7, 2021, 2:51pm
2
Problem isn’t as much in passing the argument, but in argument naming. That part is returning new function.
return (args[1]) => addTogether(args[0], args[1]);
Taking out just the function definition and writing it in a longer syntax, it would look like:
function(args[1]) {
return addTogether(args[0], args[1])
}
What would make the whole args[1]
the variable name, and what is cause of the syntax error.
1 Like
Thanks for the answer… but how do I know which function definition to use. When should I use the longer syntax ?
Is there a general rule?
sanity
September 9, 2021, 5:58am
4
I don’t think there’s any specific rule regarding that. The longer syntax example was to show better what is happening here. That it is not really passing args[1]
to the function, but defining new function - which would expect to use that name as variable name.
system
Closed
March 10, 2022, 5:58pm
5
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.