Conditionally initializing a constant in Javascript

前端 未结 4 1688
[愿得一人]
[愿得一人] 2020-12-15 02:42

ES6 onwards we have const.

This is not allowed:

const x; //declare first
//and then initialize it
if(condition) x = 5;
else x = 10;
         


        
4条回答
  •  感动是毒
    2020-12-15 03:35

    If ternary operator isn't an option for its unreadability, the only other option is IIFE, which is cumbersome but can be read fluently:

    const x = (() => {
      if (condition)
        return 5
      else
        return 10
    })();
    

    The semantics of const is that it is assigned once. It should be let for this use case:

    let x;
    if(condition) x = 5;
    else x = 10;
    

    From my personal experience, ~95% of variables are const. If a variable has to be be let, just let it be itself; the probability of bugs caused by accidental reassignments is negligible.

提交回复
热议问题