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

Define a variable in JavaScript as a block

In Swift, I can do this to define a variable:

let foo: String = {
    if bar {
        return "42"
    } else {
        return "43"
    }
}()

How can I define a variable like this in JavaScript? I know that you can define a variable as undefined and redefine it in the if block, but that’s an ugly syntax IMO, since "foo" would get repeated 3 times instead of 1 in the Swift example:

let foo

if (bar) {
    foo = "42"
} else {
    foo = "43"
}

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

>Solution :

If you’re just setting the value conditionally you can use a ternary expression:

const foo = bar ? '42' : '43'

You could also use a function for more complex logic:

let bar = true;
const foo = computeFoo(bar);

function computeFoo(bar) {
  if (bar) {
    return "42";
  }
  return "43";
}

console.log(foo); // 42

Or an IIFE:

let bar = true;
const foo = (() => {
  if (bar) {
    return "42";
  }
  return "43";
})()

console.log(foo); // 42
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