Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a variable in JavaScript as a block

Tags:

javascript

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"
}
like image 954
Tamás Sengel Avatar asked Oct 24 '25 10:10

Tamás Sengel


2 Answers

If the logic is short enough you could use a conditional operator:

let foo = bar ? "42" : "43"

If the logic is more complicated, then i personally would do the last example you showed. But one other alternative you could consider is using an immediately invoked function expression:

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

This creates an anonymous function, calls it immediately, and then whatever it returns gets assigned to foo.

like image 85
Nicholas Tower Avatar answered Oct 26 '25 01:10

Nicholas Tower


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

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

You could 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
like image 28
ray hatfield Avatar answered Oct 26 '25 01:10

ray hatfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!