Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are there curly brackets in the parameters when declaring this javascript function? (Node, MongoDB in model.js)

I'm looking at someone else's functioning Javascript code. Why are there curly brackets in the parameters when declaring a function? eg:

function createUser({username, password, name, weight}, f) {};

Is this just enforcing and renaming keys that would be in a passed in object? This is in model.js so perhaps it has something to do with validation?

Follow up questions: How can I get this not to error out when I try to compile this on my machine? I get "SyntaxError: Unexpected token {" at the first of these strange brackets.

like image 220
bplittle Avatar asked Dec 19 '22 22:12

bplittle


1 Answers

It's an ES6 destructuring assignment.

This syntax declares a function with two parameters.

The values of the username, password, name and weight properties of the object passed as the first argument will be available through the variables username, password, name and weight in the function body.

The second argument will be available through the variable f.

For example:

(function ({a,b}, c) {
  return [a,b,c];
})({a:1, b:2, d:"ignored"}, 3); // [1,2,3]
like image 133
Oriol Avatar answered Mar 23 '23 00:03

Oriol