DEV Community

loading...

Clean Code #1 : React, Javascript

moni_coder profile image Moni ・1 min read

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

Discussion (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
Forem Open with the Forem app