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 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 🙂

Ryan Sukale

Ryan is just a regular guy next door trying to manage his life and finances.