Andrew Andrew - 1 year ago 105
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';

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download