Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

129
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda