Javascript conditionally add property to object in an easy way

Today, we will explore how to conditionally add property or members to an object in JavaScript based on specific conditions.

In this article, we’ll show you how to use if statements, the spread operator, and other methods to achieve this.

Start improving your JavaScript skills today and master the art of conditionally adding properties to objects!

Conditionally add a property to an object

To conditionally add a property to an object we can use the && operator.

For example:

const trueCondition = true;
const falseCondition = false;

const obj = {
  ...trueCondition && { apples: "fruits" },
  ...falseCondition && { dogs: "animals" },
};

console.log(obj);

Output:

{ apples: 'fruits' }

The reason is this, the trueCondition is true, so the apples property is added to the obj object. However, the falseCondition is false, so the cabbages property is not added to the obj object.

Here’s the example code with parentheses:

const trueCondition = true;
const falseCondition = false;

const obj = {
  ...(trueCondition && { apples: "fruits" }),
  ...(falseCondition && { cabbages: "vegetables" }),
};

console.log(obj);

Note: Parentheses are not required for evaluating these expressions. However, it is helpful to use them to ensure that the spread operation applies to the complete result of the expression.

How to conditionally add a property to a JavaScript object?

There are several ways to conditionally add a properties or members to an object in JavaScript.

Solution 1: Use if statement

An if statement is a way to run a specific piece of code only if a particular condition is met.

It follows a basic structure or syntax like this:

if (condition) {
  //the code to be executed if condition is true
}

In an if statement, there is a condition that can be either true or false. If the condition is true, a specific set of codes will be executed.

However, if the condition is false, that set of code will be skipped.

For instance, let’s just say you have an object x and you want to add a property y with value of 100 to it, and if a certain condition is true:

var x = {};
var someCondition = true;

if (someCondition) {
  x.y = 100;
}

console.log(x);

In this example, we have an object called “x” and a variable called “someCondition” that is initially set to true. The if statement checks if “someCondition” is true.

If it is true, then a specific code block enclosed in curly braces {} is executed, adding a property “y” with a value of 100 to the object “x.”

When we check the value of “x” in the console, we can see that it now has the property “y” with a value of 100.

Output:

{ y: 100 }

However, if we change the value of “someCondition” to false, the code block within the curly braces {} will not be executed, and the object “a” will remain unchanged.

For example:

var x = {};
var someCondition = false;

if (someCondition) {
  x.y = 100;
}

console.log(x);

Output:

{}

Solution 2: Use the spread operator and logical AND short circuit evaluation

Here’s an example that demonstrates how to use the spread operator and logical AND short circuit evaluation to conditionally add a property to an object.

const someCondition = true;
const x = {
  ... (someCondition && {y: 100})
}
console.log(x); 

Here, we have a variable someCondition which is set to true. We also have an object x which uses the spread operator (…) and logical AND short circuit evaluation to conditionally add a property y with value 100 if someCondition is true.

Output:

{ y: 100 }

Since someCondition is true, the property y with value 100 is added to object x. When we log the value of a to the console, we can see that it now has a property x with a value of 100.

Solution 3: Use the && operator

The && operator is a special tool in JavaScript used for reasoning with true/false values. It’s one of three logical operators in the language, alongside || (OR) and ?? (nullish coalescing).

For example:

const someCondition = true;
const x = {
  ... (someCondition && {y: 100})
}
console.log(x); 

In this example, we have a variable called “someCondition” set to true. We also have an object named “x” that uses the spread operator (…) and a logical AND check to add a property “y” with a value of 100 only if “someCondition” is true.

Here’s the output:

{ y: 100 }

When we view the value of “x” in the console, we can see that it now has the property “y” with a value of 100.

Solution 4: Use the ternary operator

The ternary operator is a handy shortcut in programming that acts like a shorter version of an if statement.

It is a condition that is followed by a question mark (?).

It is an expression to execute if the condition is true, followed by a colon (:).

Additionally, it is an expression to execute if the condition is false.


const someCondition = true;
const x = {
  ... (someCondition ? {y: 100} : {})
}
console.log(x); 

We have here the object “x” which uses the spread operator (…) and the ternary operator to conditionally add a property y with value 100 if someCondition is true.

Since someCondition is true, the property y with value 100 is added to object x.

Output:

{ y: 100 }

As a result, we can see that it now has a property y with value 100.

Why conditionally add a property to an object is important in Javascript?

This concept is important because it helps you customize your JavaScript application based on user conditions.

By adding properties like team affiliation or special menu items for specific user roles, you can create a personalized user experience.

This ensures that each user gets relevant features and enhances their satisfaction with your application.

How to conditionally add a value to an array?

To conditionally add a value to an array is can be done using ternary operator.

For example:

const trueCondition = true;
const falseCondition = false;

const fruits = [
  ...(trueCondition ? ["apples"] : []),
  ...(falseCondition ? ["bananas"] : [])
];

console.log(fruits);

Output:

[ 'apples' ]

Conclusion

In conclusion, this article explores various methods to conditionally add property or members to objects in JavaScript.

The techniques discussed include using if statements, the spread operator, logical AND short circuit evaluation, and the ternary operator.

Conditionally adding properties to objects is crucial in JavaScript as it allows for customization based on user conditions.

By adding properties such as user roles or personalized features, you can enhance the user experience and provide relevant functionality.

Moreover, this article briefly mentions how to conditionally add values to arrays using the ternary operator, providing an example of dynamically populating an array based on specific conditions.

We are hoping that this article provides you with enough information that helps you understand the JavaScript conditionally add property to object.

You can also check out the following article:

Thank you for reading itsourcecoders 😊.

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.

Caren Bautista


Technical Writer at PIES IT Solution

Responsible for crafting clear, well-structured, and beginner-friendly content across the platform. Handles the writing, proofreading, and editorial review of tutorials, guides, and documentation to ensure every article is accurate, readable, and easy to follow.

Expertise: Technical Writing · Content Creation · Documentation · Editorial Writing · JavaScript · TypeScript · Python · Python Errors · HTTP Errors · MS Excel
 · View all posts by Caren Bautista →

Leave a Comment