Search code examples
javascriptfor-loopconstantsvarlet

what is the difference between these two codes. One return error and second one return no error?


When I use var in the loop I get no error.

function reverseString(str) {
  for (var reversedStr = "", i = str.length - 1; i >= 0; i--) {
    reversedStr += str[i];
  }
  return reversedStr;
}
console.log(reverseString("hello"))
//OUTPUT --------> olleh

when I use let in the loop I get an error.

function reverseString(str) {
  for (let reversedStr = "", i = str.length - 1; i >= 0; i--) {
    reversedStr += str[i];
  }
  return reversedStr;
}
console.log(reverseString("hello"))
//OUTPUT -------->Uncaught ReferenceError: reversedStr is not defined


Solution

  • Scoping.

    In your first example, var reversedString is function-scoped, and accessible in the whole function.

    In your second example, let reversedString is block-scoped, and only accessible in the for loop.