Question:
How to assign multiple const variables in single declaration in JS

Problem 

I'm rather new to react/JS therefore this question my sound somehow dumb:


I need multiple variables that are set depending on a location(System variable). Those variables should be constants as they should never change for a given instance.


This is my current solution, it works but it feels very wrong to define variables inside other variable declarations. It also seems to not be possible to declare footerWidth and footerAltText as constants without an initial value.


<Box

    as='img'

    width={footerWidth}

    justifyContent='center'

    alignContent='center'

    src={footerLogoSource}

    alt={footerAltText}

 />


Those attributes are provided by my features.ts:


export let footerWidth: string

export let footerAltText: string

export const footerLogoSource: string =

  getAppConfig().contextPath +

  (() => {

    switch (getAppConfig().landesvariante) {

      case Variante.SN:

        footerWidth = '30%'

        footerAltText = 'lorem ipsum'

        return '/assets/kofin_eu_logo.svg'

      case Variante.BB:

        footerWidth = '20%'

        footerAltText = 'lorem ipsum 2'

        return '/assets/logo_bb.svg'

      default:

        return null

    }

  })()


One solution would be to make 3 switch-case configurations for the 3 variables, but that would lead to alot of duplicated code...

Is there a proper way to do this?


Solution

Here's an approach using >array destructuring


const [footerWidth, footerAltText, footerLogoSource] = (() => {

  const config = getAppConfig();


  switch (config.landesvariante) {

    case Variante.SN:

      return ['30%', 'lorem ipsum', `${config.contextPath}/assets/kofin_eu_logo.svg`];

    case Variante.BB:

      return ['20%', 'lorem ipsum 2', `${config.contextPath}/assets/logo_bb.svg`];

    default:

      return [undefined, undefined, null];

  }

})();


You can use object destructuring as well


const { width: footerWidth, altText: footerAltText, logo: footerLogoSource } = (() => {

  const config = getAppConfig();

  switch (config.landesvariante) {

    case Variante.SN:

      return {

        width: '30%',

        altText: 'lorem ipsum',

        logo: `${config.contextPath}/assets/kofin_eu_logo.svg`

      };

    case Variante.BB:

      return {

        width: '20%',

        altText: 'lorem ipsum 2',

        logo: `${config.contextPath}/assets/logo_bb.svg`

      };

    default:

      return {logo: null};

  }

})();


Suggested blogs:

>Javascript Error Solved: Property 'id' does not exist on type 'T'

>Why highlighted table row using class not working in JavaScript?

>How to rename an object key based on the condition in JavaScript?

>How to sort an array based on another array in Javascript?

>Javascript: Modal not closing with a button


Nisha Patel

Nisha Patel

Submit
0 Answers