What is the difference between var and let in Typescript?

后端 未结 4 1526
旧时难觅i
旧时难觅i 2020-12-28 12:13

I submitted a question on stack overflow asking how I could stop the putTestQuestionResponses() function from executing IF a previous version was already executing.

4条回答
  •  失恋的感觉
    2020-12-28 12:36

    var variables in JavaScript are function scoped. This is different from many other languages (C#, Java, etc.) where the variables are block scoped. If you bring a block scoped mindset to JavaScript, you would expect the following to print 123, instead it will print 456:

    var foo = 123;
    if (true) {
        var foo = 456;
    }
    
    console.log(foo); // 456
    

    This is because { does not create a new variable scope. The variable foo is the same inside the if block as it is outside the if block. This is a common source of errors in JavaScript programming. This is why TypeScript (and ES6) introduces the let keyword to allow you to define variables with true block scope. That is, if you use let instead of var, you get a true unique element disconnected from what you might have defined outside the scope. The same example is demonstrated with let:

    let foo = 123;
    if (true) {
        let foo = 456;
    
    }
    
    console.log(foo); // 123
    

提交回复
热议问题