Andrew Andrew - 1 month ago 4x
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 = || 'Buddy'

return name;

I was expecting the
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 && ? : 'Buddy';


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