Conditionally initializing a constant in Javascript

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

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

    const x = condition ? 5 : 10;
    

提交回复
热议问题