Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
forEach and assign to variable

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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!