Andrew Andrew - 2 months ago 6
Javascript Question

How to use properties of optional object argument

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 complex:

var name = (options !== undefined && options.name) ? options.name : 'Buddy';

Answer

You can simplify the check to options && options.name || 'Buddy' because every object is truthy.