Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating Const value using a function

I want to achieve similar result to this code:

  const myResult = useMemo(
    () => {
      var arr = ["el1"]
      if(someCondition){
        arr.push( "el2", "el3")
      }
      return arr 
    }, [someCondition]
  )

but without using useMemo(), just simple const (it is simple so can be recomputed with every render and I want to maintain a code as simple as it’s possible)

I was thinking about something like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  const myResult = () => {
      var arr = ["el1"]
      if(someCondition){
        arr.push( "el2", "el3")
      }
      return arr
  }

but in that case array is a function returning array of strings, not array of strings it self.

I know I can do it like this

const myResult = someCondition ? ["el1", "el2", "el3"] : ["el1"]

but I don’t like here that "el1" is duplicated in code…

Is it possible to achieve my goal or I overthink the problem?

>Solution :

You have at least four choices:

  1. Add the () necessary to call the function you wrote to replace the useMemo call,

    or
  2. Don’t use a function wrapper at all (this is what I’d do)

    or
  3. As deceze suggested for this specific case, use spread notation to spread out either your el2, el3 array or an empty one

    or
  4. If your real use case requires temporary variables, etc., use an anonymous/standalone block rather than a function.

Here’s #1:

const myResult = (() => {
    const arr = ["el1"];
    if (someCondition) {
        arr.push( "el2", "el3");
    }
    return arr;
})();

Here’s #2 (which is what I’d do):

const myResult = ["el1"];
if (someCondition) {
    myResult.push( "el2", "el3");
}

Here’s #3:

const myResult = ["el1", ...(someCondition ? ["el2", "el3"] : [])];

Here’s #4 (only makes sense if you have temporary variables within the block):

const myResult = ["el1"];
{
    if (someCondition) {
        myResult.push( "el2", "el3");
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading