Home > database >  Besides scope, what's the difference between declaring a variable inside a loop vs outside?
Besides scope, what's the difference between declaring a variable inside a loop vs outside?

Time:08-24

While studying JS, I came across this problem/solution in CodeWars.

Problem: Create a function that turns a string into a "Mexican Wave." For example: "hello" ==> ['Hello', 'hEllo', 'heLlo', 'helLo', 'hellO'].

Solution (splitStr INSIDE loop):

function wave(str) {
  let waveArr = [];
  for (let i = 0; i < str.length; i  ) {
    const splitStr = str.split(""); // INSIDE loop
    if (splitStr[i] !== " ") {
      splitStr[i] = splitStr[i].toUpperCase();
      waveArr.push(splitStr.join(""));
    }
  }
  console.log(waveArr);
  return waveArr;
}
wave("hello");
// returns ['Hello', 'hEllo', 'heLlo', 'helLo', 'hellO']

I noticed the function returns something different if splitStr is declared OUTSIDE the loop: ['Hello', 'HEllo', 'HELlo', 'HELLo', 'HELLO']. Instead of only capitalizing one letter per iteration, it capitalizes multiple. Why does this happen?

splitStr OUTSIDE loop:

function wave(str) {
  let waveArr = [];
  const splitStr = str.split(""); // OUTSIDE loop
  for (let i = 0; i < str.length; i  ) {
    if (splitStr[i] !== " ") {
      splitStr[i] = splitStr[i].toUpperCase();
      waveArr.push(splitStr.join(""));
    }
  }
  console.log(waveArr);
  return waveArr;
}
wave("hello");
// returns ['Hello', 'HEllo', 'HELlo', 'HELLo', 'HELLO']

CodePudding user response:

When a variable is declared outside of a loop it's state is maintained for all loop instances. Take a counter for example:

var counter = 0;
for(var i=0;i<10;i  ){
    counter = counter   1;
    console.log(counter);
}

since we declared the variable counter outside of the loop, it's value is maintained for each instance of the loop resulting in it incrementing up.

For the same example if we declare counter within the loop:

for(var i=0;i<10;i  ){
    var counter = 0;
    counter = counter   1;
    console.log(counter);
}

the counter variable will be destroyed and recreated every instance of the loop. This results in the log statement always printing 1.

So to summarize, variables created within a loop will only exist for the duration of that instance of the loop, while variables declared outside of the loop will continue to exist for all instances of the loop.

  • Related