What is the use case for var in ES6?

前端 未结 4 1205
既然无缘
既然无缘 2020-11-27 07:24

If the let keyword introduces a proper implementation of block scope, does var any longer have a use case? I am looking at this from a software des

4条回答
  •  一整个雨季
    2020-11-27 07:44

    You can use var if you want to deconstruct something into the function scope, for example a conditional:

    if (Math.random() > 0.5)
      var {a,b} = {a: 1, b: 2}
    else 
      var {a,b} = {a: 10, b: 20}
    
    // Some common logic on a and b
    console.log(a, b)
    

    With let you would have to write something like

    let result;
    
    if (Math.random() > 0.5)
      result = {a: 'foo', b: 'bar'}
    else 
      result = {a: 'baz', b: 'qux'}
    
    // Using const might make more sense here
    let {a, b} = result; 
    // Some common logic on a and b
    console.log(a,b)
    

提交回复
热议问题