loading...

re: Keyword arguments in JavaScript VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Javascript doesn’t have kwargs support like python. But the popular work around is, function foo ({arg1=10, arg2='bar'}) { // do your stuff here }
 

Thanks!
But what exactly does this do, doesn't this only supply properties for the object?

 

ES6 has this support only. So, get supported all browsers you may need to use babel.

Ok, but what does this code do?
Can you give some examples on how to use these defined properties in the function itself?
Thanks!
Cheers!

This is argument destructuring. It's sort of a pattern match on the keys of an object.

It can be done in the body of a function too, for example:

const obj = { width: 400, height: 300 };

const { width, height } = obj;

console.log(width + " x " height);
// => 400 x 300

You can then add to that by providing fallbacks or defaults for keys that may not exist in the object you are destructuring. The variables will only take the default if there isn't a key in the object.

const obj = { width: 400, height: 300 };

const { width = 100, height = 100, depth = 100 } = obj;

console.log(width + " x " height + " x " + depth);
// => 400 x 300 x 100

You can then move this to the function definition:

function printDimensions({ width = 100, height = 100, depth = 100 }) {
  console.log(width + " x " height + " x " + depth);
}

printDimensions({ width: 400, height: 300 });
// => 400 x 300 x 100
printDimensions({});
// => 100 x 100 x 100
printDimensions({ width: 10, height: 20, depth: 30 });
// => 10 x 20 x 30

Hope that helps. Check out this post for more detail: wesbos.com/destructuring-default-v...

code of conduct - report abuse