Allowing if else blocks during assignment

Often times we want to assign different values based on condition but the ternary operator falls short as there nested cases and many more.

I think it will be very convenient to have if-else block for assignment
E.g

const value = if (condition) {
//...
return someValue;
} else {
//...
return someOtherValue;
}

The current workaround we have are:

  1. Declaring variable using let and then assigning it later
    E.g
let a;
if(condition) {
  a = someValue;
} else {
  a = someOtherValue;
}
  1. Creating functions or IIFE
let a = functionToGetValue();

// Or

let a = (function () {
  if(condition) {
    return someValue;
  } else {
    return someOtherValue;
  }
})();

Would love to know your thoughts on this

I believe you can currently achieve this with:

if(condition) {
    var a = someValue
}
else {
    var a = someOtherValue
}
console.log(a)

It works because of var's lexical scoping.

See https://github.com/tc39/proposal-do-expressions

2 Likes

Yep, this surely works but I think we're past a point where it is safe to say var should be avoided.
Also my idea let's us create variables using const

Thank you very much, this looks promising, will check this out more in detail