Home > Blockchain >  Understanding the use of CONST within Looped Array with JavaScript
Understanding the use of CONST within Looped Array with JavaScript

Time:01-03

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>

CodePudding user response:

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.

CodePudding user response:

Variables inside a loop gets redeclared each iteration

  • Related