I’m a bit new to javascript, I’d like my function to take in parameters and associate
them by name,
myFunction(width = 50, height = 20);
myFunction(height = 20, width = 20)
myFunction(width = 50); // height will get some default value
so then I can have:
function myFunction()
{
var width; // this will somehow get the variable that was passed in or set default value
var height; // this will somehow get the variable that was passed in or set default value
}
Is there a way to possibly do this in javascript?
Also, I’ve seen syntax of the form
ball: {
x: '124',
y: '22',
}
but I have no idea what it’s called.
Maybe I could use this syntax somehow, and create some kind of object that I then pass into my function.
But what I’m looking for is:
- Pass parameters into a function by name, not by order.
- Make all parameters passed into the function optional; if they are not passed in assign a default value.
What’s the best/cleanest way to do this?
Passing an object as single parameter is the way to go.
Example:
The
||shorthand (boolean OR) will set each value to0if it is not provided. That is, it will assign0ifoptions.widthevaluates tofalsewhich is the case when it is not defined (i.e.options.widthisundefined).Whether this is sufficient depends on what kind of values are allowed. E.g. if
falseis a valid value, you have to explicitly test forundefined.Another and arguably more handy way to define default values would be to use an
extendfunction:This copies all properties of object
bto objectaif they are not present.It lets you set default values this way
regardless of the value.
This is the way jQuery uses. It provides an
$.extend[docs] function which is commonly used when developing plugins to provide default settings. A good example of a function which accepts named and optional parameters is$.ajax[docs].