Pass unknown number of parameters to JS function [duplicate] - javascript

This question already has answers here:
What is the difference between call and apply?
(23 answers)
Closed 7 years ago.
A pattern in some javascript libraries is to be able to pass any number of parameters to a function:
functiona(param1)
functiona(param1, param2, param3)
functiona(param1, param2)
I have an array of unknown length, and I'd like to pass all the array items as parameters to a function like functiona(). Is this possible? If so, what is the syntax for doing this?

What you want is probably Function.prototype.apply().
Usage:
var params = [param1, param2, param3];
functiona.apply(this, params);
As others noted, functiona declaration may use arguments, e.g.:
function functiona()
{
var param1 = this.arguments[0];
var param2 = this.arguments[1];
}
But it can use any number of normal parameters as well:
function foo(x, y)
{
console.log(x);
}
foo.apply(this, [10, 0, null]); // outputs 10

Use arguments:
The arguments object is an Array-like object corresponding to the
arguments passed to a function.

Yep, all parameters passed to a JavaScript function can be accessed using the arguments array within the function.
function foo () {
console.log(arguments[0]); // -> bar
console.log(arguments[1]); // -> baz
}
foo('bar', 'baz');

Related

What exactly is function expression? [duplicate]

This question already has answers here:
What is the difference between a function expression vs declaration in JavaScript? [duplicate]
(5 answers)
Why JavaScript function declaration (and expression)?
(5 answers)
Why use named function expressions?
(5 answers)
Closed 1 year ago.
I thought before that function expression can be any function that is store in some variable. For example, this is function expression, because function is stored in func variable.
let func = function() {
console.log(5);
};
And here's function expression, because callback function is stored in function's paremeter callback.
function func(callback) {
callback();
};
func(function() {
console.log(5);
});
//That's what I mean:
//let callback = function() {...}
But... recently I've found out that this callback function can also be considered as function expression. Why? This function isn't stored in some variable.
let arr = [18, 50];
let obj = {
name: 'Karina',
};
arr.forEach(function func(value) {
console.log(`${this.name} is ${value} years old`);
}, obj);
So, my question is...What exactly make function function expression?
I thought before that function expression can be any function that is store in some variable.
No. The variable to store to does not matter. The let func = …; is not part of the function expression, the function expression is only the part (expression) that comes in the middle.
let func = function() {
// ^^^^^^^^^^^^
console.log(5);
//^^^^^^^^^^^^^^^^^^
};
//^
This function isn't stored in some variable.
Actually there's no difference between your second and third snippet. You're passing the function constructed from the expression to a function, regardless how that function is declared (with parameters, with rest syntax, without parameters, or as a builtin like forEach).
But yes, you can have function expressions completely without variables, like in
!function() {…}();
// ^^^^^^^^^^^^^^
void function() {…};
// ^^^^^^^^^^^^^^
(function() {…})();
// ^^^^^^^^^^^^^^
Basically, function expressions are just the literal syntax (as in: object literal, string literal) for function objects.
I'm also learning about functional programming and found out that using a function as a value is indeed a function expression, as you said, by assigning an anonymous function to a variable. But I think the main difference relies on the function declaration being hoisted right? So context comes to play and all of that fun stuff :)

How to generate a function argument list with variable number of arguments programmatically? [duplicate]

This question already has answers here:
JavaScript variable number of arguments to function
(12 answers)
Closed 5 years ago.
I would like to call a function, lets say test_func that accepts variable number of arguments. (like this function http://locutus.io/php/array/array_intersect_assoc/)
Please note I would like to avoid modifying the receiver function! All the answers so far require modifying the receiver function, just as the linked "possible dupes". I would like to programmatically generate the argument list itself. (eg pass variable number of objects)
I do not know in advance how many arguments I will have. How can I generate a variable length argument with objects?
var v1 = {test:1};
var v2 = {test2:2};
var obj_arr = [v1,v2];
console.log(test_func (obj_arr.join(",")));
//in my case this should be the equivalent of test_func (v1,v2);
function test_func (object_arg) {
return(arguments.length);
}
//should return 2!
If you're in an ES5 environment you can use arguments:
function test() {
var param1 = arguments[0];
var param2 = arguments[1];
// arguments is array like, you can iterate over it with a loop
}
If you are in an ES6 environment you can either use the rest operator as suggested by Suren or also use the arguments variant as above - depending on the convention of you're team.

Is there a way to pass part of inputs into function? [duplicate]

This question already has answers here:
Is there a way to provide named parameters in a function call in JavaScript?
(12 answers)
Closed 5 years ago.
Suppose I have a function as this:
function test(a, b, c, d) {
...
}
Is there a way that I can pass my inputs into the function as follows:
test(a:1,c;2)
Named values doesn't support in a function, you have 2 options:
Pass undefined value to unused variable like test(1, undefined, 2, undefined)
Modified the parameters as an object like test(obj) and use obj.a, obj.b,... to pass the values
You can not as you exactly suggested, but you could have your function take an object with your arguments as fields.
Ex:
function test(myArguments) {
if (myArguments.a) {
// do something with myArguments.a
}
...
}
Call as:
test({a: 1, b: 2});

How to pass a function in another function with variadic arguments with javascript? [duplicate]

This question already has answers here:
Calling dynamic function with dynamic number of parameters [duplicate]
(10 answers)
Closed 7 years ago.
I have a pre-process function, here's an example function
function preprocess (msg, fct) {
alert(msg);
fct(???);
}
I need to execute the function fct in the preprocess function, but fct not always has the same number of parameters. I am not a pro in javascript but I think there are 2 ways to achieve that :
explicit call with an object
function preprocess (msg, fct, obj) { ... }
usage : preprocess ('hello', myfct, {firstparam: 'foo', secondparam: 'bar'});
using the argument inner property of the function
anyways i might have the theory, i am not able to code both the case above. Is it possible to achieve what I need using both the ways ? if yes, could you provide a minimum example of each to show me the way ?
You can pass the arguments at the end in variadic form, and use the arguments object to get what you need:
function preprocess (msg, fct /*, ...as*/) {
var as = [].slice.call(arguments, 2);
alert(msg);
fct.apply(this, as);
}
preprocess(msg, fct, a, b, c); // fct(a, b, c)

Passing arguments of a function to another function in javascript [duplicate]

This question already has answers here:
Passing arguments forward to another javascript function
(5 answers)
Closed 9 years ago.
I have a method defined, say abc, which accepts a function name, say xyz and the arguments to that function as its arguments. Now, the abc method needs to call xyz with the arguments received.
xyz can be any method and could be having any number of arguments, also, xyz cannot be using arguments keyword. rather, the arguments for the method should be passed as separate variables.
Ex: xyz will be defined as:
var xyz = function(a,b){//code for processing a and b}
I am calling the abc method with the first argument as the function to be invoked and rest of the arguments as arguments to be passed to the function while calling it. In abc, I am making use of arguments keyword to access the dynamic number of arguments sent. But from there I am not sure how to call the next function with the arguments.
Use the apply method of functions to call it with a variable argument list:
function abc(funcName) {
funcName.apply(null, [].slice.call(arguments, 1));
}
You could also pass along your current context by supplying the first argument:
function abc(funcName) {
funcName.apply(this, [].slice.call(arguments, 1));
}

Categories

Resources