I was wondering if it is possible to pass a value to a specific parameter by for example specifying its name, not taking into account if this parameter is the first, the second or the 100th one.
For example, in Python you can do it easily like:
def myFunction(x, y):
pass
myFunction(y=3);
I really need to pass a value to a specific parameter of which I don't know necessarily its position in the parameters enumeration. I have searched around for a while, but nothing seems to work.
No, named parameters do not exist in javascript.
There is a (sort of) workaround, often a complex method may take an object in place of individual parameters
function doSomething(obj){
console.log(obj.x);
console.log(obj.y);
}
could be called with
doSomething({y:123})
Which would log undefined
first (the x
) followed by 123
(the y
).
You could allow some parameters to be optional too, and provide defaults if not supplied:
function doSomething(obj){
var localX = obj.x || "Hello World";
var localY = obj.y || 999;
console.log(localX);
console.log(localY);
}
Passing parameters this way isn't possible in JavaScript. If you need to do this, you're better off passing an object into your function, with properties set to represent the parameters you want to pass:
function myFunction(p) {
console.log(p.x);
console.log(p.y);
}
myFunction({y:3});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With