You don't need the top-level else if you're going to be returning from the function; you can just short-circuit and return early, otherwise this can be simplified a bit and still be pretty readable, I think:
var firstName = object.firstName
var lastName = object.lastName
if (!lastName || firstName === lastName) {
return firstName
}
return firstName ? [lastName, firstName].join(', ') : lastName
You also may want to have something up-front though if neither is set, like an if (!firstName || !lastName) return 'unknown' or the like; otherwise you're returning undefined which is maybe what you want.
Maybe easier is just using an array in the first place:
var name = []
if (object.lastName) name.push(object.lastName)
if (object.firstName) name.push(object.firstName)
return name.join(', ')
Or you could get wacky with something like that:
var name = ['lastName', 'firstName'].map(function (key) {
if (object.hasOwnProperty(key)) {
return object[key]
}
})
return name.filter(Boolean).join(', ')
But that's way harder to follow the intent than the simple case, I think. There are ways to do this with nested ternaries, but I really find a nested ternary hard to read; to me, it's better to add some lines and be explicit and understandable.
return firstName === lastName ? firstName : firstName && lastName ? lastName + ", " + firstName : (firstName || lastName);