Tell us what’s happening:
I am getting a syntax error when using the code below. See ERROR. I am placing the …args operator in the function as explained in the instructions. I assume this is the function they’re talking about and not the return function within the outer SUM function. Also, I don’t know what the purpose of “use strict” is. I’ve seen it it in several challenges, but this is the first time it’s caused problems. Why is it causing problems? Where should I put …args? Do I need the prefix? Thanks.
Your code so far
const sum = (function(...args) {
"use strict";
return function sum(x, y, z) {
const args = [ x, y, z ];
return args.reduce((a, b) => a + b, 0);
};
})();
console.log(sum(1, 2, 3)); // 6
FREECODECAMP ERROR:
SyntaxError: unknown: Non-simple parameter in strict mode (1:22)
> 1 | const sum = (function(...args) {
| ^
2 | "use strict";
3 | return function sum(x, y, z) {
4 | const args = [ x, y, z ];
VISUAL STUDIO CODE ERROR
SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.
The outer function is an IIFE, just runs the code inside it immediately. If you log out the variable sum you can see it holds the returned inner function signature.
Right now, the inner function has a fixed number of parameters, your task is to make the function accept a dynamic number of arguments, i.e. it can’t have a fixed number of parameters (must use the rest operator).
Info on the error message you are seeing.
Side note: Why does the last test of the assignment say “The sum function uses the … spread operator on the args parameter.”, shouldn’t it say rest not spread?
For the x,y,z are you referring to the return function sum(x,y,z) or the const args = [x.y.z] or both? These are what came with the challenge.
The “use strict” comes up automatically in the position it’s in. When I delete it I get the same answers (6) for all test cases.
This is a function definition using rest for it’s parameter, it can be called with as many arguments as needed.
function sum(...args) {
return args.reduce((a,b) => a + b);
}
console.log(sum(1,2,3));
This is a function with a fixed number of parameters, being called using spread on the argument.
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers));
It is confusing that the assignment says use spread on the sum function. To me, that implies when the function is called, spreading the arguments into it. As opposed to, using rest on the parameters of the function definition. Correct me if i am wrong, but i think the wording on the assignment’s last test is incorrect. Also, spread is first introduced in the assignment following this assignment.