What is the use case for var in ES6?

前端 未结 4 1206
既然无缘
既然无缘 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:56

    Practically there are some use-cases I found for myself.

    Sometimes you may want to declare variable in try-catch like so:

    try {
        //inits/checks code etc
        let id = getId(obj);
    
        var result = getResult(id);
    } catch (e) {
        handleException(e);
    }
    
    //use `result`
    

    With let the result declaration would be before try, which is a bit early and out of context for the author and a reader of the code.

    Same is for conditional declarations:

    if (opts.re) {
        var re = new RegExp(opts.re);
        var result = match(re);
        if (!result) return false;
    }
    
    //use result here safely
    

    With let this code would be a bit forced to complain "good style", though that might be impractical.

    Also I can imagine the case where you would like to use variables belonging to the loop block:

    for (var x = 0; x < data.width; x++) {
        if (data[x] == null) break;
        //some drawing/other code
    }
    
    //here we have the `x` pointing to the end of data
    

    Someone with high beauty standards may consider that untidy, I myself prefer lets, but if the code I edit already contains vars - that is natural to use them and makes coding easier.

提交回复
热议问题