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

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

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 Denunciar

0

Variables inside a loop gets redeclared each iteration

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