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

94
Views
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 answers
Answer question

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 Report

0

Variables inside a loop gets redeclared each iteration

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!