
Aug 20, 2021

Conditional spread operator in object and array literals in JavaScript
Conditional rendering in jsx using logical “&&” operator.
If you’re a React developer, chances are you’re familiar with the common idiom of rendering component conditionally.
In the example above, if props.eventId is missing, the expression below will yield the undefined .
JSX is designed with such cases in mind , and if an expression returns false or undefined , React will treat it as a noop and not render anything.
Using logical && operator in place of if..else statement is somewhat a controversial topic in JS community. But in case of JSX, the expression looks concise and improves the readability. From a pragmatic programmer viewpoint, I would favor readability in this particular case.
Sometimes I’m faced with a task when I need to compose an object or an array, where some properties or items should be added depending on the condition evaluation. Let’s see if the && logical operator can help us with this.
Add items to an array based on the condition
For example, I need to create an array of items, where each item represents an Integration object from @sentry/react or @sentry/browser npm packages.
The trick here is to add the trailing .filter(Boolean) method, which will remove all those falsy fantom items.
When you need to add a collection of items to an array all of which are based on the single condition (e.g deployment.debug ), you can use this variation of the above example.
This approach might look strange for those who are unfamiliar with the “rest/spread” syntax . Compare it with the following conventional approach based on if/else blocks usage. Here, you get a mix of declarative and imperative approaches, where array literal declaration followed by push() mutation statements. Personally, I don’t like it.
Someone may argue that the latter example is more readable, and it does not rely on those strange syntactic constructs. I would agree that too much syntax sugar added to the language forces the developer to write too smart code which harmful, but this is not that case.
Augment object with extra properties based on the condition
The same approach could be applied when composing an object. Consider the simple example first:
We augment object with two extra properties email and name , but only when the user expression is not falsy. Otherwise, object will contain only the lang property.
More complex example would be composing an object, that represents a MongoDB query.
Notice, that it’s not the same with the example below. In case of a falsy condition, you’ll end up with a new property added to the object, but having null or undefined value. It’s not the same to the object without a property altogether. Finally, you might compose an invalid MongoDB query object, which will yield completely different results.
The only equivalent solution is to use the conventional approach with if..else blocks. But, IMO, it looks too verbose.
Wrapping up
Choose whatever solution you like more. It’s jus at matter of preference.
But, please, don’t blindly follow advices, rules, guides on the Internet. Yes, usually it’s better to use if..else statements in favor of logical && operator. But it’s not a hard rule, and final choice is always up to you, depending on the project needs.
More from Alexey Samoshkin
Full-stack software engineer, Kharkov, UA
About Help Terms Privacy
Get the Medium app

Alexey Samoshkin
Text to speech
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Conditional spread element
When cond is true, I want both extra and user info.
When cond is false, only userInfo is needed.
The issue is when cond is false, I get
TypeError: (intermediate value)(intermediate value)(intermediate value)[Symbol.iterator] is not a function
My understanding is that I am not allowed to use a boolean as a spread element, in this case ...false .
But ...( cond ? extraInfo : {} ) doesn't seem to work either.
What is going on?
- ecmascript-6
- ternary-operator

5 Answers 5
Just make it
Demo with true
var cond = true; var extraInfo = [ { a: 11, b: 25 }, { a: 12, b: 34 }, { a: 1, c: 99 } ]; var userInfo = [ { z: 8 }, { z: 10 }, ...(cond ? extraInfo : []) ]; console.log( userInfo );
Demo with false
var cond = false; var extraInfo = [ { a: 11, b: 25 }, { a: 12, b: 34 }, { a: 1, c: 99 } ]; var userInfo = [ { z: 8 }, { z: 10 }, ...(cond ? extraInfo : []) ]; console.log( userInfo );
- can change the conditional operator to ...(cond && extraInfo || []) – Aswin Ramesh Dec 19, 2017 at 8:33
- Nice, but why!? If it accepts filled object why not empty one? – Akxe Dec 19, 2017 at 8:33
- Now it makes sense! So objects are not iterable without the [Symbol.iterator] protocol that's why ...{} wouldn't work? – Liren Yeo Dec 19, 2017 at 8:34
- @AswinRamesh That also works, thanks, I will add that as well. – gurvinder372 Dec 19, 2017 at 8:34
- 1 @AswinRamesh No, don't do that. It's longer, more confusing, and works only if extraInfo is truthy. – Bergi Dec 19, 2017 at 8:36
Conditionally spread an entity to Object
Conditionally spread an entity to Array

- So, what is the actual difference between spreading into object vs array? When trying to spread into array, one gets Uncaught TypeError: boolean false is not iterable (cannot read property Symbol(Symbol.iterator)) . – Qwerty May 20, 2020 at 14:04
- 2 I didn't know this can be done. Really concise in certain use cases. Nice! – Daniel San Aug 16, 2020 at 17:17
- @Qwerty, the problem here, with the object, that is causing the TypeError , is that an expression like false && somethingElise will always return false , that is not spreadable. You need to use ternary opeator here too, with an empty object if false , similar to the array example. – Emanuele Scarabattoli Mar 5, 2022 at 14:01
const extraInfo = [ { a: 11, b: 25 }, { a: 12, b: 34 }, { a: 1, c: 99 } ]; const userInfo = [ { z: 8 }, { z: 10 }, ]; const cond = true; let getMyValue = cond ? [].concat(extraInfo, userInfo) : userInfo; console.log(getMyValue)

Another way:
cond is true:
var extraInfo = [ { a: 11, b: 25 }, { a: 12, b: 34 }, { a: 1, c: 99 } ] var cond = true; var userInfo = [ { z: 8 }, { z: 10 }, ...(cond && extraInfo || []) ] console.log(userInfo);
cond is false:
var extraInfo = [ { a: 11, b: 25 }, { a: 12, b: 34 }, { a: 1, c: 99 } ] var cond = false; var userInfo = [ { z: 8 }, { z: 10 }, ...(cond && extraInfo || []) ] console.log(userInfo);
- 1 Why not use a proper ternary operator? – Bergi Dec 19, 2017 at 8:36
- question of taste. – Faly Dec 19, 2017 at 8:39
- question of correctness, simplicity and performance. Of course you can have a horrible taste for them :-) – Bergi Dec 19, 2017 at 8:39
- Are you sure ternary operator is more performant ? If you cannot understand it, that doesn't mean that it's horible – Faly Dec 19, 2017 at 8:47
- Yes it is, because it does not have to evaluate the truthiness of the value returned by the cond && extraInfo expression. It's one operation, not two. (Also: write what you mean) – Bergi Dec 19, 2017 at 8:49
let check this
const extraInfo = [ { a: 11, b: 25 }, { a: 12, b: 34 }, { a: 1, c: 99 } ]; const userInfo = [ { z: 8 }, { z: 10 }, ]; const cond = false; let getMyValue = cond ? [].concat(extraInfo, userInfo) : userInfo; console.log(getMyValue)

- Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference. – Mat Dec 19, 2017 at 12:20
- Hi, I place my ans like bottom of the section , no issues let's check this – dinesh kumar Dec 19, 2017 at 12:31
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged javascript ecmascript-6 ternary-operator or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
Hot Network Questions
- How can I find out which sectors are used by files on NTFS?
- Checking system vs. SEPA and the like
- Why is this sentence from The Great Gatsby grammatical?
- How can I explain to my manager that a project he wishes to undertake cannot be performed by the team?
- Can I tell police to wait and call a lawyer when served with a search warrant?
- What video game is Charlie playing in Poker Face S01E07?
- Why are physically impossible and logically impossible concepts considered separate in terms of probability?
- How to prove that the supernatural or paranormal doesn't exist?
- How to calculate lattice parameter?
- Do I need a thermal expansion tank if I already have a pressure tank?
- Calculating probabilities from d6 dice pool (Degenesis rules for botches and triggers)
- How do I align things in the following tabular environment?
- Bulk update symbol size units from mm to map units in rule-based symbology
- Applications of super-mathematics to non-super mathematics
- Does Counterspell prevent from any further spells being cast on a given turn?
- What can a lawyer do if the client wants him to be acquitted of everything despite serious evidence?
- Salesforce queuable implementation
- Is it possible to develop the Ubuntu kernel on the same computer that one works on?
- Are there tables of wastage rates for different fruit and veg?
- Why are Suriname, Belize, and Guinea-Bissau classified as "Small Island Developing States"?
- Transgenic Peach DNA Splicing
- Has 90% of ice around Antarctica disappeared in less than a decade?
- QGIS - Countif function
- Why is there a voltage on my HDMI and coaxial cables?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .
Conditional Spread Syntax In JavaScript
Spread syntax , in JavaScript, lets you expand arrays, objects and even strings succinctly. It is one of the features in JavaScript that I miss the most when working in other programming languages.
In this article, I will show how you can expand any JavaScript literal conditionally .
Conditionally expand an object
Idiomatic syntax is
Explanation
Consider these two objects
You can merge them together like so,
Say I add a boolean variable expand . obj2 should be expanded only when expand is true.
objMerged value is
Try false.
Conditionally expand a string to an object
When you apply the spread operator on a string inside {} , it returns an object.
eg value is
Therefore, you can use the same syntax that you use for conditionally expanding an object.
Conditionally expand an array
Consider these two arrays
You can merged these arrays like this,
Say I add a boolean variable expand . arr2 should be expanded only when expand is true.
Unfortunately, this will not work if condition, expand , is false. You will get the error.
error: TypeError: false is not iterable
The reason is in case of array and string, the ... operator requires an iterable. When the condition is false, the () expression is empty, in turn, the ... operator complains, “Where is my iterable?”
Therefore, the correct syntax is
The ternary operator provides an empty array for the failing case.
Conditionally expand a string to an array
When you apply the spread operator on a string inside [] , it returns an array.
Value of eg is [ "a" , "b" , "c" ] .
Therefore, just like an array, if you try to use logical and operator && , you will get the error.
The correct syntax is
Here expandedStr will evaluate to an empty array [] .
You can see a working examples and run them at this link .
It’s output is
Keep Reading
- Iterate Over An Array And Remove Elements
- When To Use useState vs useReducer Hook In React
- Build Your Own Hook To Access RESTful API
- javascript 4
Email Newsletter

DEV Community

Posted on Jun 11, 2020 • Originally published at blog.agney.dev
Conditionally spread into Object/Array - Javascript
There comes a time when we want to add more fields/elements into an array or object when it satisfies a certain condition. This blog is an exploration of how and why.
Spreading into an Array
isWinter is a boolean variable and you need to add winterEssentials if it's true and nothing otherwise.
We need an empty array at end because we cannot spread undefined or null into an array (they are not iterables). Spreading an empty array into another just keeps the array intact.
Spreading into an Object
Rest spread into object is a Stage 4 ECMA proposal and is implemented in most browsers .
It mimics the behavior of existing Object.assign operator.
You will notice here that resorting to a conditional operator isn't necessary. This is because rest spread for objects tries to wrap any primitive it finds to an object.
Guide to Type Coercion in JavaScript
So the expression (isHacker && hacker) returns undefined which our spread operator converts to {} and spreading an empty array into an object results in nothing.
That's conditional spread.
Top comments (0)

Templates let you quickly answer FAQs or store snippets for re-use.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .
Hide child comments as well
For further actions, you may consider blocking this person and/or reporting abuse
- What's a billboard?
- Manage preferences
Visualizing Promises and Async/Await 🤯
☝️ Check out this all-time classic DEV post

Add an Options Page to Chrome Extension
Carlo Gino Catapang - Feb 24

How To Mock Only One Function From Module
Chris - Feb 24


Converting Real-World Colors to a Digital Format
Adam Nathaniel Davis - Feb 22
Pixelating Images With React/JavaScript
Adam Nathaniel Davis - Feb 23
Once suspended, boywithsilverwings will not be able to comment or publish posts until their suspension is removed.
Once unsuspended, boywithsilverwings will be able to comment and publish posts again.
Once unpublished, all posts by boywithsilverwings will become hidden and only accessible to themselves.
If boywithsilverwings is not suspended, they can still re-publish their posts from their dashboard.
Once unpublished, this post will become invisible to the public and only accessible to Agney Menon.
They can still re-publish the post if they are not suspended.
Thanks for keeping DEV Community safe. Here is what you can do to flag boywithsilverwings:
boywithsilverwings consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy.
Unflagging boywithsilverwings will restore default visibility to their posts.

We're a place where coders share, stay up-to-date and grow their careers.
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.
It works, as (...) - the spread operator spreads nothing if the operand is an empty array.
b) Conditional properties inside object literals
Related tags, about author.

Ishaan Madan
Ishaan is an experienced Wordpress/PHP Lead Developer, he has good knowledge of HTML, CSS, PHP, Wordpress, Jquery and AJAX. His hobbies are playing basketball and reading about defence.
More From Oodles
Code reusability: the new success formula for software development, reusable codes can solve software growth issues related to both business and technical challenges., priyansha singh | 21-feb-2023, how fleet management technologies are streamlining business operations, fleet management systems have proven to be a game changer for organizations seeking to achieve maximum productivity and cost efficiency., priyansha singh | 16-feb-2023, scaling your business in 2023 with micro saas: tips and trends, micro saas virtually refers to small, pocket-sized saas that is focused on particular business needs., priyansha singh | 30-jan-2023, ready to innovate let's get in touch.
Recaptcha is required.
Ready to innovate?
Let's get in touch.
Name is required
Enter a valid Email address
Email is required
Please remove URL from text
Comment is required
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.
Amit Merchant Verified ($10/year for the domain)
A blog on PHP, JavaScript, and more
Conditionally spreading objects in JavaScript
September 13, 2022 · ⋆ JavaScript
In JavaScript, if you want to populate an object with some properties from another object, you can use the spread operator ( ... ) to do so.
For example, you can do something like this.
But what if you want to conditionally spread the properties of an object? For example, you want to spread the properties of an object only if a certain condition is met.
I recently learned about a neat trick to do this in JavaScript. So, let’s see how we can do this.
Short-circuiting the spread operator
Essentially, we can short-circuit the spread operator using the && operator. So, if the condition is met, the spread operator will be executed and the properties of the object will be spread. Otherwise, it will be skipped.
Here’s an example.
As you can tell, in the example above, the user object will only get “spread” when the isActive is true and since logical AND ( && ) evaluates operands from left to right, returning immediately with the value of the first falsy operand it encounters; if all values are truthy, the value of the last operand is returned.
There’s one caveat though. The first operand must be a boolean value. So, if you want to use a variable as the first operand, you have to convert it to a boolean value using, let’s say, the Boolean() function.
And that’s how you can conditionally spread objects in JavaScript!
» Share: Twitter , Facebook , Hacker News

👋 Hi there! I'm Amit . I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!
More on similar topics
Change tab bar color dynamically using JavaScript
Convert any value to a boolean in JavaScript
Generating slugs using one line of code in JavaScript
Human-readable date difference in JavaScript
Download my eBook

(Includes PHP 8.1 and 8.2)
Get the latest articles delivered right to your inbox!
No spam guaranteed.
Follow me everywhere
More in "JavaScript"
Aliasing destructured variables in JavaScript
Recently Published
Today I Learned — font shorthand in CSS NEW
Animated gradient text in CSS
Dry running Git commands
Conveniently toggle and add Tailwind CSS classes in Chrome DevTools
Building LinkSnatch — A bookmarks app with Next.js and Tailwind CSS
Top Categories
- Skip to main content
- Skip to search
- Skip to select language
- Get MDN Plus
- English (US)
Conditional (ternary) operator
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy . This operator is frequently used as an alternative to an if...else statement.
An expression whose value is used as a condition.
An expression which is executed if the condition evaluates to a truthy value (one which equals or can be converted to true ).
An expression which is executed if the condition is falsy (that is, has a value which can be converted to false ).
Description
Besides false , possible falsy expressions are: null , NaN , 0 , the empty string ( "" ), and undefined . If condition is any of these, the result of the conditional expression will be the result of executing the expression exprIfFalse .
A simple example
Handling null values.
One common usage is to handle a value that may be null :
Conditional chains
The ternary operator is right-associative, which means it can be "chained" in the following way, similar to an if … else if … else if … else chain:
This is equivalent to the following if...else chain.
Specifications
Browser compatibility.
BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
- if statement
- Nullish coalescing operator
- Optional chaining
- Making decisions in your code — conditionals
- Expressions and operators
Conditionally spread into Object/Array - Javascript
There comes a time when we want to add more fields/elements into an array or object when it satisfies a certain condition. This blog is an exploration of how and why.
Spreading into an Array
isWinter is a boolean variable and you need to add winterEssentials if it’s true and nothing otherwise.
We need an empty array at end because we cannot spread undefined or null into an array (they are not iterables). Spreading an empty array into another just keeps the array intact.
Spreading into an Object
Rest spread into object is a Stage 4 ECMA proposal and is implemented in most browsers .
It mimics the behavior of existing Object.assign operator.
You will notice here that resorting to a conditional operator isn’t necessary. This is because rest spread for objects tries to wrap any primitive it finds to an object.
Guide to Type Coercion in JavaScript
So the expression (isHacker && hacker) returns undefined which our spread operator converts to {} and spreading an empty array into an object results in nothing.
That’s conditional spread.
You can share the article if you found it useful:
WebMentions

- ← Let's make a Picture in Picture Countdown timer on the Web
- One Signal Notifications on Gatsby →
Join the Squad
I sent out a newsletter every month containing information that I find notable and useful. Unsubscribe any time you want & Feel free to browse Archives

JavaScript in Plain English

Jan 14, 2022
Member-only
How to Conditionally Add a Member to a JavaScript Object?
Sometimes, we want to conditionally add a member to a JavaScript object.
In this article, we’ll look at how to conditionally add a member to a JavaScript object.
Spread Operator
We can use the spread operator to spread an object into another object conditionally.
For instance, we can write:
We use the && operator to return the object only when condition is true .
If the object is returned then it’ll be spread into obj .
And so we get:
as a result.
Instead of using the && operator, we can also use the ternary operator by writing:
We return an empty object when condition is false instead of null .
Object.assign
Also, we can use the Object.assign method to merge an object into another object.
We have the condition check in the 2nd argument of the Object.assign method.
We return the object only when condition is true .
Otherwise, null is returned.
Since condition is true , we have the same result for obj .
We can add properties to an object conditionally with the spread operator or the Object.assign method.
We can use the ternary operator or && operator to specify what to add given the condition.
More content at plainenglish.io . Sign up for our free weekly newsletter . Get exclusive access to writing opportunities and advice in our community Discord .
More from JavaScript in Plain English
New JavaScript and Web Development content every day. Follow to join 3M+ monthly readers.
About Help Terms Privacy
Get the Medium app

John Au-Yeung
Web developer. Check out https://thewebdev.info . Email me at [email protected]
Text to speech

IMAGES
VIDEO
COMMENTS
... trick where one can conditionally apply an object property in JavaScript using ES6's spread syntax. The spread operator ( ... ) allows…
Conditional spread operator in object and array literals in JavaScript · Conditional rendering in JSX using logical “&&” operator · Add items to
5 Answers 5 · can change the conditional operator to ...(cond && extraInfo || []) · Nice, but why!? If it accepts filled object why not empty one?
When you apply the spread operator on a string inside {} , it returns an object. ... Therefore, you can use the same syntax that you use for
You will notice here that resorting to a conditional operator isn't necessary. This is because rest spread for objects tries to wrap any
a) Conditional elements inside Array. ... It works, as (...) - the spread operator spreads nothing if the operand is an empty array. > [.
Essentially, we can short-circuit the spread operator using the && operator. So, if the condition is met, the spread operator will be executed
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?)
Spreading into an Object ... Rest spread into object is a Stage 4 ECMA proposal and is implemented in most browsers. It mimics the behavior of
We can use the spread operator to spread an object into another object conditionally. ... We use the && operator to return the object only when condition is true