0

function x({ name = 'abc' }) {
  console.log(name);
}

x({ name: null })

How to provide default value for above case which handles all falsey value for name? I was expecting that when name: null will be replaced by abc but apparently not the case? It's only working in the below case

function x({ name = 'abc' }) {
  console.log(name);
}

x({  })

Wondering if it's possible to provide default value for all falsey value? Of course we can check for the condition explicitly but wondering if there is any alternatives

1
  • what about name = name || 'abc'? As long as name is falsey it will work, though it will work with '' as well, which might not be intended. Commented Nov 9, 2018 at 6:51

3 Answers 3

3

Default parameter values are only applied when the value is undefined. You'd have to implement such logic yourself.

function x({name}) {
  if (!name) {
    name = 'abc';
  }
  console.log(name);
}

x({ name: null })

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

2 Comments

So, what's happen if name contains value false (x({ name: false }))?
@TânNguyá»…n: Correct, means we can't really rely on !name but to explicitly handle specific falsey value instead
2

null is intentional, undefined is not.

In other words, providing null means the value is null, so 'abc' will not be set as the default value.

This should do the trick:

function x({ name }) {
   !(!!name) && (name = 'abc'); 
      
   console.log(name);
}
    
x({ name: null })

3 Comments

In other words default value for parameters are only meant for undefined instead of falsey values?
Arguably you can also intentionally pass undefined though ;)
@FelixKling: True that! now default value for parameters don't seems to be really that helpful ha!
0

How does redefining suits you in case, when the value was null?

function x({ name }) {
  name = name ? name : 'abc';
  console.log(name);
}

x({ name: null });
x({ name: 'asd' });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.