0

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
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 3
    Does this answer your question? [What's the difference between using "let" and "var"?](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var) – Mady Daby Apr 20 '21 at 11:44

1 Answers1

0

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.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147