What is the problem with the code

What’s the problem: I want the function to return the standard form of number in array. But the function is returning empty array

My code so far:

function standardForm(num){  
  num = num.toString();
  let numArr = []; 
  let unit = '';
  for(let i = num.length - 1; i==0; i--){
    numArr.push(num[i].concat(unit))
    unit.concat('0')
  }
  return numArr.reverse();
}
console.log(standardForm(12))

Example:

Input: standardForm(37)
Output: [30,7]

Input: standardForm(123)
Output: [100, 20, 3]

Input: standardForm(20)
Output: [20,0]

for(let i = num.length - 1; i===0; i--){
Your loop only runs if i is 0. So your loop is not running.

So what should i do?
I even put i==0 in the for loop. But still did’nt work

If i = num.length - 1, and i decrements with each iteration of your loop, when should the loop stop running. Sometimes it helps to think of when the loop should stop, and use that to determine when it should run.

I want the loop to stop when i == 0;
I mean i want the loop to iterate through every element of the array but in backward direction

So if it stops at i == 0, and i is currently larger than 0, how do you write that?
Remember that the second parameter of a for loop determines the condition under which the loop runs.

Maybe i <= 0. //ignore this... my post had to be at least 20 words

but still not working

Yeah i got it; i>=0 will work

1 Like

Then the function would only run if i was less than 0. i starts as greater than 0.

Did you get it working?

Yes i got it. there was a silly mistake

1 Like