My code:
function test() {
let value: number;
for (let i = 0; i < 10; i++) {
value = i;
console.log(value);
}
return value;
}
test();
And got this:
Variable 'value' is used before being assigned
I found this very odd, as I had seen other similar problems that either used a callback or a Promise or some other asynchronous method, while I used just a synchronous for loop.
---------------------------------- Some update ------------------------
function test() {
let value: number;
for (let i = 0; i < 100; i++) {
// a() is very expensive and with some effects
const result = a(i)
if(i===99) {
value = result
}
}
return value;
}
value
variable will indeed be initialized. That is why you get the error. Assigning any initial value will fix the error. – Callable