Conditionally initializing a constant in Javascript

前端 未结 4 1677
[愿得一人]
[愿得一人] 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:09

    Your problem, as you know, is that a const has to be intialised in the same statement that it was declared in.

    This doesn't mean that the value you assign to your constant has to be a literal value. It could be any valid statement really - ternary:

    const x = IsSomeValueTrue() ? 1 : 2;
    

    Or maybe just assign it to the value of a variable?

    let y = 1;
    if(IsSomeValueTrue()) {
        y = 2;
    }
    
    const x = y;
    

    You could of course assign it to the return value of a function, too:

    function getConstantValue() {
        return 3;
    }
    
    const x = getConstantValue();
    

    So there's plenty of ways to make the value dynamic, you just have to make sure it's only assigned in one place.

    0 讨论(0)
  • 2020-12-15 03:30

    I suggest this solution with a Singleton Pattern implementation:

    var Singleton = (function () {
        var instance;
    
        function createInstance() {
            // all your logic here
            // so based on your example:
            // if(condition) return 5;
            // else return 10;
        }
    
        return {
            getInstance: function () {
                if (!instance) {
                    instance = createInstance();
                }
                return instance;
            }
        };
    })();
    
    const x = Singleton.getInstance();
    
    0 讨论(0)
  • 2020-12-15 03:31

    Assuming that the const is going to be declared in both instances, you could use a ternary assignment:

    const x = condition ? 5 : 10;
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题