Conditionally elements inside Array using Spread Operator
Posted By : Ishaan Madan | 28-Dec-2017
As a developer often, we often encounter scenarios where we need conditional elements in an Array or an object literal. To achieve the objective most of us often use one of the two ways:
1. Using "push()" method.
2. Using "Splice() method".
However both the above methods would need to be enclosed in a specific condition to work. With push() having a limitation to add an element only at the end of an array.
With the advent of ECMAScript 6, we may use a more feasible way to add elements to an array conditionally. The method use spread and ternary operator for the purpose and is explained below.
a) Conditional elements inside Array.
const cond = false;
const arr = [
...(cond ? ['a'] : []),
'b',
];
// ['b']
It works, as (...) - the spread operator spreads nothing if the operand is an empty array.
> [...[], 'a']
[ 'a' ]
b) Conditional properties inside object literals
const cond = false;
const obj = {
...(cond ? {a: 1} : {}),
b: 2,
};
// {b: 2}
Thanks
More From Oodles
Ready to innovate? Let's get in touch
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Ishaan Madan
Ishaan, a skilled technical project manager, excels at breaking down complex projects into manageable tasks. With a background in both technology and project management, he offers a unique perspective to every project he undertakes. His effective communication skills enable him to collaborate seamlessly with both technical and non-technical stakeholders, ensuring everyone is aligned towards shared objectives. He has hands-on experience in utilizing agile methodologies like Scrum and Kanban to drive project management and foster team collaboration. He leverages project management tools such as JIRA, Trello, and Clickup to monitor progress, manage tasks, and facilitate communication among team members and stakeholders. Moreover, his proficiency in full-stack development empowers him to comprehend the technical aspects of projects and provide guidance to developers when necessary. He demonstrates expertise in utilizing popular Python frameworks like Django and Flask, along with data analysis and manipulation libraries such as NumPy and Pandas. On the front-end, Ishaan adeptly employs JavaScript libraries like React and Angular to craft visually appealing and user-friendly interfaces. Additionally, he possesses proficiency in HTML, CSS, and JavaScript for designing responsive and mobile-friendly layouts.