This is just an example that I want to understand. I know there is a better way to select the last element from the array, but I don't know why it works that way.
const numbers = [1, 2, 3];
let exampleId: number;
numbers.forEach(function(number) {
exampleId = number;
});
console.log(exampleId);
Why do I get the error "Variable 'exampleId' is used before being assigned." in the line from console.log?
CodePudding user response:
Maybe the interpreter doesn't take into account that the array numbers
is not empty in your code.
Because, if it were empty, for sure the variable exampleId
would be used before being assigned.
(If the array is empty, the code inside the forEach loop is never executed, and the variable is never assigned)
CodePudding user response:
The assignment is scoped within the forEach
loop; If numbers
have no values, exampleId
would never get defined. TS is essentially warning you about that, as you cannot call a variable that has yet to be defined.
Solution 1:
Initialise your variable with a value
let exampleId = 0;
Solution 2:
Use non-null assertions, although I'd suggest against them
console.log(exampleId!);
With this solution we're essentially telling TS to not worry about it, as there will surely exist a value; That, in other words, remove the type safety, reason why I'd suggest going with option 1.
CodePudding user response:
The way to select the value of the last element from an array is
function lastElementOfArray(arr = []) {
return arr.length > 0
? arr[ arr.length - 1 ]
: undefined
;
}
The reason you get Variable 'exampleId' is used before being assigned.
is because there's no guarantee that the Array.forEach()
callback that assigns a value to exampleId
will ever be invoked (e.g., when the array numbers
has a length of 0).
And so, you get that message on the line
console.log(exampleId)