Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where can I get info on the object parameter syntax for JavaScript functions?

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?

like image 710
Verdagon Avatar asked May 29 '12 18:05

Verdagon


People also ask

What is the syntax of JavaScript function object?

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.

What is the parameter of a function JavaScript?

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.

How do you check if the function has a parameters JavaScript?

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.

Which is the parameter name parameter in JavaScript?

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.


1 Answers

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.

like image 115
Bergi Avatar answered Nov 18 '22 19:11

Bergi