Alexey Samoshkin

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

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store

Alexey Samoshkin

Text to speech

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?

Felix Kling's user avatar

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 );

gurvinder372's user avatar

Conditionally spread an entity to Object

Conditionally spread an entity to Array

Purkhalo Alex's user avatar

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)

dinesh kumar's user avatar

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);

Faly's user avatar

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)

Liam's user avatar

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 .

Hot Network Questions

js conditional spread operator

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

Email Newsletter

DEV Community

DEV Community

Agney Menon

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)

pic

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

Visualizing Promises and Async/Await 🤯

☝️ Check out this all-time classic DEV post

codegino profile image

Add an Options Page to Chrome Extension

Carlo Gino Catapang - Feb 24

zirkelc profile image

How To Mock Only One Function From Module

Chris - Feb 24

bytebodger profile image

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.

DEV Community

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.

Author Image

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

Caricature of Amit Merchant sketched by a friend

👋 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

PHP 8 in a Nutshell

(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

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.

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

Jithin Sathyan

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

js conditional spread operator

JavaScript in Plain English

John Au-Yeung

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

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store

John Au-Yeung

Web developer. Check out https://thewebdev.info . Email me at [email protected]

Text to speech

IMAGES

  1. 8 ways to use the Spread operator in JavaScript.

    js conditional spread operator

  2. Playing with JavaScript Object clone

    js conditional spread operator

  3. Pin on Node.js

    js conditional spread operator

  4. React Conditional Rendering

    js conditional spread operator

  5. spread operator angular 2+ :: Merge Two arrays

    js conditional spread operator

  6. JavaScript

    js conditional spread operator

VIDEO

  1. JCB 3DX Talab ke andar work

  2. Butch Charvet

  3. Pokemon: Journeyshipping

  4. Showroom Inauguration Part 4 of 4

  5. Hill with Boulders Cutting for A New Mountain Road-JCB Backhoe

  6. [Arknights] Lore accurate Yato

COMMENTS

  1. Conditional Object Properties Using Spread in JavaScript

    ... trick where one can conditionally apply an object property in JavaScript using ES6's spread syntax. The spread operator ( ... ) allows…

  2. Conditional spread operator in object and array literals in JavaScript

    Conditional spread operator in object and array literals in JavaScript · Conditional rendering in JSX using logical “&&” operator · Add items to

  3. Conditional spread element

    5 Answers 5 · can change the conditional operator to ...(cond && extraInfo || []) · Nice, but why!? If it accepts filled object why not empty one?

  4. Conditional Spread Syntax In JavaScript

    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

  5. Conditionally spread into Object/Array

    You will notice here that resorting to a conditional operator isn't necessary. This is because rest spread for objects tries to wrap any

  6. Conditionally elements inside Array using Spread Operator

    a) Conditional elements inside Array. ... It works, as (...) - the spread operator spreads nothing if the operand is an empty array. > [.

  7. Conditionally spreading objects in JavaScript

    Essentially, we can short-circuit the spread operator using the && operator. So, if the condition is met, the spread operator will be executed

  8. Conditional (ternary) operator

    The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?)

  9. Conditionally spread into Object/Array

    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

  10. How to Conditionally Add a Member to a JavaScript Object?

    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