source code here github.com/jayanthbabu123/fun...
In JavaScript, a function is a block of code to perform a particular task. It is a grouping of reusable code that eliminates repetition.
When you call a function in JavaScript, you can pass in any number of arguments, regardless of what the function declaration specifies. There is no function parameter limit.
Let’s create a function that accepts two parameters
In the above function, if we pass any number of arguments, the result is always the same because it will take the first two parameters only.
So we need to write a function that accepts any number of arguments. we can handle it in two ways
arguments object (ES5)
Rest parameters (ES6)
arguments object (ES5)
In Javascript, arguments is a local JavaScript object variable that is available in all non-arrow functions. arguments is an Array-like object accessible inside functions that contain the values of the arguments passed to that function.
Let's create a function that accepts n number of parameters in ES5:
The above screenshot represents the arguments object in the console.
Since the arguments object isn’t an array, we first have to convert it into an array using the Array.from method before we can use the reduce method.
The arguments object was not available in arrow functions.
Rest Parameters (ES6)
The rest parameter provides an easier and cleaner way of working with an indefinite number of arguments. Let’s rewrite the above example with a rest parameter.
Using the rest parameter, which is the same syntax as the spread operator, we can pass an indefinite number of parameters to our function.
The main difference between rest parameters and the arguments object is:
All the array methods like map, sort, and filter can be applied directly on the rest parameters array but not on the arguments object. To use Array methods on the arguments object, it must be converted to a real array first.
The rest parameter is a more declarative syntax and is more straightforward in how the function is being utilized.
The arguments object has additional functionality specific to itself (like the callee property).
The arguments object is not available in arrow functions.
3 июл 2020