Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
Concise way to print empty string fallback if optionally-chained variable is undefined in string literal

Let's say I have this string literal use case:

function getClassNames(props){
    my_classNames = `class-nameA class-nameB ${props?.one} ${props?.two} class-nameC`;
    return my_classNames;
}

console.log(getClassNames({one: 'class-name-one', two: 'class-name-two'}))
  // prints: class-nameA class-nameB class-name-one class-name-two class-nameC
console.log(getClassNames({two: 'class-name-two'}))
  // prints: class-nameA class-nameB undefined class-name-two class-nameC
console.log(getClassNames())
  // prints: class-nameA class-nameB undefined undefined class-nameC

The problem is when any of props' keys is undefined, it prints undefined. I want it to print empty string instead.

One solution to this is to use short-circuit OR evaluation like this:

function getClassNames(props){
    my_classNames = `class-nameA class-nameB ${props?.one || ''} ${props?.two || ''} class-nameC`;
    return my_classNames;
}

console.log(getClassNames())
  // prints: class-nameA class-nameB   class-nameC

Or a better solution (to avoid extra spaces), to use previous solution with short-circuit AND evaluation like this:

function getClassNames(props){
    my_classNames = `class-nameA class-nameB${props?.one && ' '+props?.one || ''}${props?.two && ' '+props?.two || ''}class-nameC`;
    return my_classNames;
}

console.log(getClassNames())
  // prints: class-nameA class-nameB class-nameC

To make it more concise, I can wrap duplicates/repetitions in previous solution to a function:

function getClassNames(props){
    my_classNames = `class-nameA class-nameB${concatWithSpace(props?.one)}${concatWithSpace(props?.two)}class-nameC`;
    return my_classNames;
}

function concatWithSpace(str){
    return str && ' '+str || '';
}

console.log(getClassNames())
  // prints: class-nameA class-nameB class-nameC

Is there a more concise built-in way (syntax) to print empty string (instead of undefined) for optionally-chained variables without using the previous "not-so concise" solutions I mentioned?

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

Don't use a template string, but an array and do some processing on it:

function getClassNames(props){
    const my_classNames = ['class-nameA', 'class-nameB', props?.one, props?.two, 'class-nameC'];
    return my_classNames.filter(Boolean).join(' ');
}

This also works properly with optional parts at the begin or end, or an empty array.

about 4 years ago · Santiago Gelvez Report

0

maybe destructuring props and assigning default values?

like this:

function getClassNames({ one = '', two = '' }){
    my_classNames = `class-nameA class-nameB ${one} ${two} class-nameC`;
    return my_classNames;
}

(EDIT)

or, you can write a helper function for template literals (tagged template)

/* types textContent(stringList: TemplateStringsArray, ...valueList: unknown[]) */
function classString(stringList, ...valueList) {
    return stringList.reduce((text, string, i) => (
        text + string + (valueList[i] || '')
    ), '').replace(/ +/g, ' '); // (optional) replace multiple spaces with single
}

var one = undefined;
var two = undefined;
var three = "something";

console.log(classString`class-nameA class-nameB ${one} ${two} ${three} class-nameC`);
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!