Using let in a for loop and is not working

Tell us what’s happening:
Describe your issue in detail here.
My code runs perfectly if I use “var” inside the for loop to initiate “product” but I get an error message saying “ReferenceError: product is not defined” if I use “let” instead of “var”, why?

  **Your code so far**

function factorialize(num) {
for (let product = 1; num > 0; num--) {
  product *= num;
return product;

  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36

Challenge: Factorialize a Number

Link to the challenge:

This is an anti-pattern for loop.

First, scope. let is scoped to the nearest set of {}s so the variables declared inside of the loop head are only scoped to the loop. This means you can’t use them outside of the loop.

Now, with a for loop, you really should initialize and use a control variable, like i.


If your interested in further reading about the scope of var, let, and const:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.