My point is this:
function sum(...arguments) {
if (arguments.length === 1) {
const [firstArg] = arguments;
if (firstArg instanceof Array) {
return sum(...firstArg)
}
}
return arguments.reduce((a, b) => a b);
}
What is this ... are doing infront of arguments. And also please help me know that why const [firstArg] is given and how this is working. And please explain me instanceof in easy words. My native language is not english. Thank you so much.
CodePudding user response:
(...arguments) is the rest parameter syntax and allows a function to accept an indefinite number of arguments as an array, providing a way to represent variadic functions in JavaScript. for more information, you can read here
const [firstArg] = arguments;
is something named Destructuring assignment The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
you can read more, here
and in the last, The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value
CodePudding user response:
That's the rest syntax
:
The rest parameter syntax allows a function to accept an indefinite number of arguments as an array.
This:
const [firstArg] = arguments;
[it] makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Re instanceOf
:
The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value.
Unpacking this code:
function sum(...arguments) {
// arguments is an array thanks
// to the rest syntax. If it has a length of
// one...
if (arguments.length === 1) {
// Get the first element
const [firstArg] = arguments;
// If that element is an array
if (firstArg instanceof Array) {
// Call sum again with that element
return sum(...firstArg)
}
}
// Return the sum of the arguments
return arguments.reduce((a, b) => a b);
}
Your function could be easily simplified by flattening
the arguments, and then using reduce
to return the sum. And this way you can even have a set of single values passed in, or n multiple arrays as a single argument to the function, or a mixture of both.
function calc(...args) {
return args.flat().reduce((acc, c) => acc c, 0);
}
console.log(calc(1, 2, 3));
console.log(calc([1], 1, 2, 3));
console.log(calc([1, 2, 3]));
console.log(calc([1, 2], [1, 4, 3]));
console.log(calc([1, 2], [12, 20], [1, 4, 3]));
CodePudding user response:
This because ... is a javascript tool that allows you to put multiple parameters in a function it is called the rest parameter function.