Functionally speaking, options 1) and 2) both yield the same outcome. I believe that the Typescript compiler translates these options into identical Javascript code, or else the Javascript interpreter does so if the Typescript compiler does not perform this optimization. I am accustomed to declaring variables not within a loop in order to prevent re-declaration, which can be crucial for objects with complex constructors. This is because in option 1), the constructor and destructor are invoked for each iteration. However, option 2 presents some compelling reasons (these days) especially for more intricate objects:
- variable not accessible outside of the loop
- indicates that it will not be reassigned
- some individuals find it more concise and easier to read
What is the best practice for declaring variables (let/const) considering scope?
1)
let someVar = "";
this.array.forEach(item => {
someVar = item;
// no further reassignment of someVar
...
});
this.array.forEach(item => {
const someVar = item;
...
});