8

I am coming from Python and am really liking the way to set named parameters and default values—now it seems that ES6 allows me to do similar. But I can't see why this last call breaks:

fun = ({first=1, last=1}) => (1*first+2*last)

console.log("-----------")

console.log( fun({first:1, last:2}) )

console.log("-----------")

console.log( fun({last:1, first:2}) )

console.log("-----------")

console.log( fun() ) // Breaks

2
  • 3
    Javascript doesn't have named arguments. Object deconstruction is not the same, even if it can be used to implement something close to named arguments. You shouldn't approach them the same way. Commented May 24, 2018 at 14:07
  • it's because you are thinking of them as kwargs. It's not the same. Good answers below. Commented May 24, 2018 at 14:10

2 Answers 2

36

You need a default object.

var fun = ({ first = 1, last = 1 } = {}) => 1 * first + 2 * last;
//                                 ^^^^

console.log(fun({ first: 1, last: 2 }));
console.log(fun({ last: 1, first: 2 }));
console.log(fun());

Sign up to request clarification or add additional context in comments.

Comments

3

Cause you need an object which can be deconstructed:

fun({})

1 Comment

Like this answer because it forces me to remember that I always must pass an object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.