Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

156
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda