Conditional Object , Array creation And Conditional spread element

Yogesh D V
2 min readMar 21, 2023

--

if you’re using ES2018, The spread operator ( ... ) allows us to expand Iterable into function calls, array literals, and object literals. Spread syntax allows for some really convenient handling and duplicating of datasets without the verbosity of alternatives such as Object.assign() or Array.slice().

While recently i wanted to modify small code snippet, I picked up this nifty trick where one can conditionally apply an object property in JavaScript using ES6’s spread syntax.

Here is my realtime experience to show conditionally list of item while myAccount dropdown

Here is my existing code


.......
.....
const renderMyAccount = () => {
.......
.....
const myAccount = [
{
name: 'Order Histry',
},
{
name: 'Profile',
},
{
name: 'Shipping & Payment',
},
{
name: 'Refer a Friend',
},
{
name: 'Logout',
},
]
return myAccount.map((item)=>(
<div>
{item.name}
<div>
);

}

.......
.....

In my case i have show Refer a friend based on isReferAfriedEnabled switch flag

We can know simplified using ES6 conditional spread next but before that lets have a look on here is the regular way of spread

const renderMyAccount = () => {
....
..
const referfriend = []
if (isReferAfriedEnabled) {
referfriend.push({
name: 'Refer a Friend',
},);
}
const myAccount = [
{
name: 'Order Histry',
},
{
name: 'Profile',
},
{
name: 'Shipping & Payment',
},


...referfriend,

{
name: 'Logout',
},
]

}

See here same thing how i simplified using ES6 conditional spread

...(isReferAfriedEnabled ? [{
name: 'Refer a Friend',
}] : []),
// isReferAfriedEnabled from global state

const renderMyAccount = () => {
....
..

const myAccount = [
{
name: 'Order Histry',
},
{
name: 'Profile',
},
{
name: 'Shipping & Payment',
},


...(isReferAfriedEnabled ? [{
name: 'Refer a Friend',
}] : []),


{
name: 'Logout',
},
]

}

This code can feel clever and clear and may be difficult to perceive at first view, which is normally something I‘m opposed to using, but the value it makes in front of other developers is worthwhile in my experience. Once you wrap your head around it, you may find it useful too!!!

we can use same thing in Array as well

// isReferAfriedEnabled from global state

const renderMyAccount = () => {
....
..

const myAccount = [
'Order Histry',
'Profile',
'Shipping & Payment',


...(isReferAfriedEnabled ? [
'Refer a Friend',
] : []),


'Logout'
]

return myAccount.map((itemNme)=>(
<div>
{itemNme}
<div>
);

}

--

--

Yogesh D V
Yogesh D V

Written by Yogesh D V

I am E-Commerce Full Stack Engineer /Full Cycle developer.My skills are HTML5, CSS3, JavaScript, reactJs, redux, vue.Js,Node.Js

No responses yet