How to initialize local variable

Tell us what’s happening:
I am doing one with algorithms and I am a bit confused because given my code below when I do not initialize price to anything, the result for my code NaN. if I set it to price = 0 then anything into that will be 0. if I set it to price = num then it is not the right answer.

Your code so far

function factorialize(num) {
  let price = num;
  for(let i = num; i >= 1; i--){
    //let i = 5; i >= 0;
    price *= i
  return price


Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ Safari/537.36

Challenge: Basic Algorithm Scripting - Factorialize a Number

Link to the challenge:

That is because when you write price *= i in your for loop, the current value of price (which would be undefined) multiplied by i would result in NaN.

That is because price starts at 0, anything you multiple it by will still be 0.

That is because your algorithm is incorrect. Think about what value you can start with that when multiplied by any number, will be the same value. That is what you should initialize price to.

Honestly, I would recommend changing price to a variable name that better describes what the resulting value is. price means nothing in context to the value returned. Since you are multiplying values, why not name the variable product?

1 Like

I struggle with choosing names for variable.

Naming is hard, annoyingly so at times.

But it is part of the process, sometimes you might change an identifier multiple times, and sometimes what it does or contains (function/variable) also changes along the way. I often find myself changing variable names after leaving the code and coming back. Suddenly it seems more obvious that it isn’t named correctly or it’s inconsistent.


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