Return vs console.log

This may be an incredibly esoteric post, but it may help one reader out there understand something that confused me for an embarrassingly long time. There is an important difference between these two ways of printing an output; the return statement and the console.log method. The defining difference being that once return has been enacted, it tells the code to stop running. In effect, return says ‘once my condition has been met, and I have returned what it is I’m expected to return, the code has achieved what it needs to, and I can now stop’. On the other hand, once console.log‘s condition has been met and it’s instruction has been executed, it will allow the code to continue on to it’s next step (if one exists).

Even though I was aware of their fundamental difference, there was one context that seemed to fox me, and usually lead me to get confused and abandon that particular approach in favour of an alternative. The context was for loops.

Image 1

Image 1 is a function that contains a simple for loop that contains a variable (i) that begins with a value of 0 and increments with each iteration until it reaches that same value of the input variable (n). With each iteration the code prints out the current value of i via the console.log method. As you can see, each iteration is printed here as each incremental value is displayed.

Image 2

Image 2 is exactly the same as image 1 apart from the console.log method has been replaced by a return statement. As you can see, the code only prints the first iteration i.e the value of i that is assigned when the variable is declared – in this case 0. This is because return statements tell the code that once they they have executed their instruction, the code has achieved what it is meant to, and there is not need to continue.

It is therefore important to be mindful when using each respective means of ‘printing’ outputs and remember that return statements may be causing stoppages in your code where you do not want them.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website at
Get started
%d bloggers like this: