Published: December 06 2022

JavaScript - Initialize Array with Conditional Values or Objects in Vanilla JS

This is a super quick post to show how to initialize an array with conditional values in JavaScript (or TypeScript).

JavaScript Ternary and Spread Operators

The ternary operator is an inline if/else statement with the syntax condition ? if : else.

The spread operator (...) can be used to copy the contents of one array into another, if the array being copied is empty nothing is copied into the new array.

Using the ternary and spread operators together we can initialize a javascript array with conditional items like this:

const myArr = ['item-1', 'item-2', ...(myCondition ? ['conditional-item-3'] : [])];


When myCondition is true the array contains three items (['item-1', 'item-2', 'conditional-item-3']), otherwise it contains two items (['item-1', 'item-2']).


Real World Example in Angular

I used this technique recently in Angular for a dynamic form that supports adding or editing a user. Form validation rules are defined for each field in an array, the password field is required when adding a new user, and is optional when editing an existing user.

Here's the code snippet from the component with the conditional item in the password validators array:

this.form = this.formBuilder.group({
    firstName: ['', Validators.required],
    lastName: ['', Validators.required],
    username: ['', Validators.required],
    // password only required in add mode
    password: ['', [Validators.minLength(6), ...(!this.id ? [Validators.required] : [])]]
});


To see the complete code for the Angular add/edit component see Angular 14 - Dynamic Add/Edit Form that Supports Create and Update Mode.

 


Need Some Vanilla JS Help?

Search fiverr for freelance Vanilla JS developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by