What is the difference b/n console.log and return

function countup (n){
for (let i = 1; i<=n; i++)
console.log(i)
}
console.log (countup(9))

function countup (n){
for (let i = 1; i<=n; i++)
return i
}
console.log (countup(9))

when i run the first code i displayed 1234…9 but when i run the second one it displayed 1
why is that

console.log is function that logs passed in argument to console.
return is keyword, which part of the return statement, used to end function execution. Once line with it is executed, the function is exited and function returns whatever is defined in the return statement. No matter ie. if after the return was additional lines with code, or if return was within loop.

1 Like

Right, as @surafealaklilu is talking about, they do different very different things. Digging into your code, you have two examples. The first one:

function countup (n){
  for (let i = 1; i<=n; i++)
    console.log(i)
}

console.log (countup(3))
// 1
// 2
// 3
// undefined

The lines 1, 2, 3… those are from the the console.log(i). It is logging out the numbers as it goes through the for loop. The last line, the undefined is because of the line console.log (countup(3)) - you are telling it to log out the return value of running that function. Since you never specified a return, it is undefined.

The second example:

function countup (n){
  for (let i = 1; i<=n; i++)
    return i
}
console.log (countup(3))
// 1

As soon as you do return i, the function is done. It returns 1, and is done. It does not continue with the rest of the function because you told it, “I have my return value, so we can stop now.” The statement console.log (countup(3)) logs out that value.

1 Like

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