Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda