Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments forward to another javascript function

Tags:

javascript

I've tried the following with no success:

function a(args){     b(arguments); }  function b(args){     // arguments are lost? }  a(1,2,3); 

In function a, I can use the arguments keyword to access an array of arguments, in function b these are lost. Is there a way of passing arguments to another javascript function like I try to do?

like image 921
Anders Nygaard Avatar asked Oct 12 '10 12:10

Anders Nygaard


People also ask

Does JavaScript pass arguments by reference?

In Pass by Reference, a function is called by directly passing the reference/address of the variable as the argument. Changing the argument inside the function affects the variable passed from outside the function. In Javascript objects and arrays are passed by reference.

What does mean => in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

Can you pass a anonymous function as an argument to another function in JavaScript?

Summary. Anonymous functions are functions without names. Anonymous functions can be used as an argument to other functions or as an immediately invoked function execution.


2 Answers

Use .apply() to have the same access to arguments in function b, like this:

console.log = function(x) { document.write(x === undefined ? undefined : JSON.stringify(x) + "<br />"); };  function a(){     b.apply(null, arguments); } function b(){     console.log(arguments); //arguments[0] = 1, etc } a(1,2,3);

You can test it out here.

like image 61
Nick Craver Avatar answered Oct 09 '22 09:10

Nick Craver


Spread operator

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

ECMAScript ES6 added a new operator that lets you do this in a more practical way: ...Spread Operator.

Example without using the apply method:

function a(...args){    b(...args);    b(6, ...args, 8) // You can even add more elements  }  function b(){    console.log(arguments)  }    a(1, 2, 3)

Note This snippet returns a syntax error if your browser still uses ES5.

Editor's note: Since the snippet uses console.log(), you must open your browser's JS console to see the result - there will be no in-page result.

It will display this result:

Image of Spread operator arguments example

In short, the spread operator can be used for different purposes if you're using arrays, so it can also be used for function arguments, you can see a similar example explained in the official docs: Rest parameters

like image 35
Walter Chapilliquen - wZVanG Avatar answered Oct 09 '22 11:10

Walter Chapilliquen - wZVanG