Be the first user to complete this post

  • 0
Add to List

Passing arguments from one function to another in javascript

You may occasionally find yourself in a situation where you need to perform some operations on the arguments of a function and then pass on the same arguments to another function for further processing. In this tiny blog post, I am going to show you how its done and why it works. The most straightforward way to achieve our goal is to use function.apply. Lets see some code.

function bar(arg1, arg2) {
    console.log(arg1 + arg2);
}

function foo() {
    bar.apply(null, arguments);
}

foo(10, 20); // Prints 30
As it turns out, all functions in javascript have a special property called apply - which is nothing but a function. You can use it to invoke the original function itself by providing it two arguments - the context(which becomes the value of 'this' in the invoked function) and an array or array-like object. Since the arguments variable within a function is an array like object, the apply function is the perfect candidate for this task. Its even pretty easy to remember that the apply function takes an array as an argument. Just think of the following line:
A for Apply, A for Array
And thats how you would pass down a function's arguments to another function without breaking a sweat :)



Also Read:

  1. css - circular profile pictures
  2. Generators and Yield in es6
  3. Testing promise sequence using mocha, chai, chai-as-promised, sinon
  4. imperative vs declarative/functional programming
  5. Error: can not find module 'underscore'