DEV Community

Passionate Coder
Passionate Coder

Posted on

Clean Code #1 : React, Javascript

Example

lets say we have a object like below

const user = {
  firstName: 'Vijay',
  lastName: 'Singh'
}
Enter fullscreen mode Exit fullscreen mode

Note : firstName and lastName can be empty string or undefined or null.

const fullName = user.firstName 
? ( user.lastName ? `${user.firstName} ${user.lastName}`: user.firstName) 
: user.lastName
Enter fullscreen mode Exit fullscreen mode

Using || Operator

const fullName = `${user.firstName || '' } ${user.lastName || ''}`.trim()
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
manuxo5 profile image
Mohit Matwaya • Edited

This one is good too 👇

const concatNames = (...names) => names.filter(Boolean).join(' ');

const fullName = concatNames(firstName, lastName)
Enter fullscreen mode Exit fullscreen mode