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. Getting started with automation testing for webrtc applications
  2. Difference between async and defer attributes in script tags
  3. Generators and Yield in es6
  4. Using es6 modules with simple examples
  5. css - align text to an image vertically
  6. Why use javascript strict mode
  7. Applying floats to inline elements
  8. Getting started with localStorage vs sessionStorage in html5