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. Progressive enhancement vs Graceful degradation
  2. Parse html response with fetch API
  3. Error: can not find module 'underscore'
  4. Pure vs Impure functions
  5. box-sizing
  6. window.onload vs document.onload
  7. Getting started with es6 iterators and iterables
  8. css specificity interview question