I have this code:
function getName(type, options) {
if (type == 'dog') {
var name = 'Rover';
}
else {
var name = options.name || 'Buddy'
}
return name;
}
alert(getName('cat'));
I was expecting the name
variable to be assigned to 'Buddy' but instead I got this error:
Cannot read property 'name' of undefined
Is there a simple way to handle this? I'm hoping for a one-line piece of code. I was thinking about using this but it seems long and unnecessarily plex:
var name = (options !== undefined && options.name) ? options.name : 'Buddy';
I have this code:
function getName(type, options) {
if (type == 'dog') {
var name = 'Rover';
}
else {
var name = options.name || 'Buddy'
}
return name;
}
alert(getName('cat'));
I was expecting the name
variable to be assigned to 'Buddy' but instead I got this error:
Cannot read property 'name' of undefined
Is there a simple way to handle this? I'm hoping for a one-line piece of code. I was thinking about using this but it seems long and unnecessarily plex:
var name = (options !== undefined && options.name) ? options.name : 'Buddy';
Share
Improve this question
edited Sep 9, 2016 at 17:49
Cave Johnson
asked Sep 9, 2016 at 17:44
Cave JohnsonCave Johnson
6,7885 gold badges41 silver badges61 bronze badges
0
3 Answers
Reset to default 6You can simplify the check to options && options.name || 'Buddy'
because every object is truthy.
Using optional parameters in es6 you can simply default it to an empty object so as not to deal with undefined.
function(type, options = {}) {
return type === 'dog' ? 'Rover' : options.name || 'Buddy';
}
You can defined a default value for the property of the argument using deconstruction (see Setting a function parameter's default value).
Adding = {}
makes the whole argument optional, allowing for getName('cat')
vs getName('cat', {})
.
Note that you are not getting whole object passed as argument - just the properties you defined: getName('bat', {somekey: 'I will not be passed to the function!'})
.
function getName(type, {name = 'Buddy'} = {}) {
if (type == 'dog') {
name = 'Rover';
}
return name;
}
alert(`
cat: ${getName('cat')},
cat with name: ${getName('cat', {name: 'Puss'})},
dog: ${getName('dog')},
dog with name: ${getName('dog', {name: 'Spot'})}`);