Be the first user to complete this post
|
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
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 ArrayAnd thats how you would pass down a function's arguments to another function without breaking a sweat :)
Also Read:
- Array filterUntil function implementation for javascript
- position: relative
- pseudo elements vs pseudo classes
- The JavaScript Prototype Property - Visualized
- Applying floats to inline elements