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

96
Visualizações
Understanding the use of CONST within Looped Array with JavaScript

My questions is about how CONST variable is used in this code.

Why does this code work if CONST variables cannot be reassigned?

I understand that as it is looping it is reassigning the value of "firstNumber". Is that correct?

or

Is it because of the way it is looping that it is not being treated as a reassignment but as a redeclaration?

**I'm new to asking questions about code, I apologize **

function twoNumberSum(array, targetSum) {
  // loop through array and assign index 0 to firstNumber
  for (var i = 0; i < array.length; i++) {
    const firstNumber = array[i];
    // loop through array and assign index 1 to secondNumber
    for (var j = i + 1; j < array.length; j++) {
      const secondNumber = array[j];

      // create condition that adds index 0 + 1 to see if it is equals to targetSum
      if ( firstNumber + secondNumber === targetSum ) {
        return [firstNumber, secondNumber];
      }
    }
  }
  return []
}

console.log(twoNumberSum([3,5,-4,8,11,1,-1,6],10));
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CODE SANDBOX</title>
</head>
<body>
This is Code SandBox.
</body>
<script src="scripts.js"></script>
</body>
</html>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The const keyword declares a variable with a constant reference to a value. In your example code, the const variable is scoped to its for block. On every iteration, the for loop terminates and creates a new enclosing scope, firstNumber is "garbage collected", and declared again(not a redeclaration, but rather a recreation) on each subsequent step.

about 4 years ago · Juan Pablo Isaza Relatório

0

Variables inside a loop gets redeclared each iteration

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