Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a value to a specific parameter without caring about the position of the parameter [duplicate]

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.

like image 705
nbro Avatar asked Sep 30 '15 14:09

nbro


2 Answers

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);
}
like image 159
Jamiec Avatar answered Nov 14 '22 21:11

Jamiec


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});
like image 43
James Thorpe Avatar answered Nov 14 '22 21:11

James Thorpe