Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Passing arguments from one function to another in javascript

You may occa­sion­ally find your­self in a sit­u­a­tion where you need to per­form some oper­a­tions on the argu­ments of a func­tion and then pass on the same argu­ments to another func­tion for fur­ther pro­cess­ing. In this tiny blog post, I am going to show you how its done and why it works.

The most straight­for­ward 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 func­tions in javascript have a spe­cial prop­erty called apply — which is noth­ing but a func­tion. You can use it to invoke the orig­i­nal func­tion itself by pro­vid­ing it two argu­ments — the context(which becomes the value of ‘this’ in the invoked func­tion) and an array or array-like object.

Since the arguments vari­able within a func­tion is an array like object, the apply func­tion is the per­fect can­di­date for this task.

Its even pretty easy to remem­ber that the apply func­tion takes an array as an argu­ment. Just think of the fol­low­ing line:

A for Apply, A for Array

And thats how you would pass down a function’s argu­ments to another func­tion with­out break­ing a sweat 🙂