The key word is "let." | Iterate Through the Keys of an Object with a for...in Statement

Tell us what’s happening:
Describe your issue in detail here.

Hello!

Can you tell me why it doesn’t work with the keyword “let”?

  **Your code so far**

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

factorialize(5);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 YaBrowser/21.9.0.1044 Yowser/2.5 Safari/537.36

Challenge: Factorialize a Number

Link to the challenge:

let scope is local for the for loop, since its defined in its body, the variable counter is only available in its body. If you were to use var, which has more wide scope, counter would be available outside the loop.
You have an interesting approach with the for loop, i must admit.

1 Like

The variable counter is scoped to the block it’s defined in. Which in this case is the loop body.

function factorialize(num) {
  for (let counter = 1; num > 0; num--){
    counter *= num;
  }
  return counter; <-- no variable called counter
}
1 Like

Right, I remembered that let counter needs to be defined locally first, and then just write the variable name inside the loop.

Thanks.

Like this:

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

factorialize(5);
1 Like

It mkes no difference what you put in as the first expression, eg

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

Or this:

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

While loop makes more sense imo

function factorialize (num) {
  let result = 1;
  while (num > 0) {
    result *= num;
    num--;
  }
  return result;
}
2 Likes

Your solution works, but you only build a semi-funcitoning for loop; you dont utilize its potential and maybe you dont even require it, so as Dan poitned out, while loop syntax would fit your needs better.
With for loop things are more explicit and it works more self-sufficient. In its parenthesis you have 3 main parameters. The first one is where you usually define a counter, loop specific values you work with during the loop and their purpose is mainly to saticfy the loop needs; the second parameter is the condition, which tells after every itereration the loop should continue or break, usually associated with the iterator variable; the 3rd segment is where you usually alternate the loop variables. In your solution, you dont use any specific loop variables, you dont define such in the first segment.

3 Likes

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