Basic "for" loop; prints undefined

let arr = []
function fact(num) {
	for(let i = num; i >= 1; i--) {
        console.log('this is ' + i)
        num = num - 1



Basic for loop. Console ends up looking like this:

I don’t understand why it prints “undefined” after 0. As I understand it i-- executes at the very end of my statement block. After num = 0 is printed, i decrements to 0. The condition statement is then evaluated and is false, so the statement block not executed and the program exits the for loop; hence, there console.log() should not print anything to the console and this is why I am not sure why undefined is printed.


What do you think that num = num - 1 is doing?
Also, it’s pretty bizarre to change the variable holding a loop condition inside the loop unless you really really know what you are doing.

Your function fact does not return a value, so when you attempt the line above it prints undefined.

It’s not hurting you, but why are you changing num in your loop?

1 Like

oh, I didn’t see that, yeah it is because the for loop was nested one layer deep into the fact() function that I completely forgot about my fact() function. That clears things up.
So a function even with an empty statement block will implicitly always try to return something, so if nothing was specified it would just return undefined, is this correct?

As to the weird function of decrementing my num variable like that in a for loop: I am trying to write a function that would evaluate the factorial of some positive integer, where zero factorial would be just 1. I wrote my if statement for the factorial function elsewhere. I broke my problem into parts. The second part being that I wanted to create an array of the numbers to be multiplied for a given factorial. I wrote the aforementioned num fact() as a small snippet to test things out on the side, saw the funky undefined and hence my confusion. In any case this array method to solve a factorial function may not be the most efficient and concise way of doing it, but it is what first came to my head and what made sense for my level. All that is left for me to do is to just multiply all contents of the array.

can I suggest a while loop?

I ended up solving the factorial algorithim. Yeah, while loop would probably be more concise. I was going to refactor my code and try a recursive function instead.