If I want to call a function like this:
moo({ a: 4 });
Normally I'd have to phrase my function definition like this:
function moo(myArgObj) {
print(myArgObj.a);
}
But this awesome syntax is totally valid in spidermonkey for defining functions:
function moo({ a, b, c }) { // valid syntax!
print(a); // prints 4
}
What is this feature?
Defining method functions The syntax for defining getters and setters uses the object literal syntax. Binds an object property to a function that will be called when that property is looked up. Binds an object property to a function to be called when there is an attempt to set that property.
The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value.
To check if a parameter is provided to a function, use the typeof operator to check if the parameter is not equal to the string "undefined" , e.g. if (typeof param !== 'undefined') . If the condition is met, the parameter was provided to the function.
JavaScript, by default, does not support named parameters. However, you can do something similar using object literals and destructuring. You can avoid errors when calling the function without any arguments by assigning the object to the empty object, {} , even if you have default values set up.
It's called destructuring. You might find the most info at MDN: Destructuring assignment (especially see Unpacking fields from objects passed as function parameter).
The ECMAScript standards discussion can be found on their wiki page, also interesting might be this blog post at dailyjs.
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