Solo Flight


#1

I wan't to make sure I understand this properly! Can anyone explain why we need to put a function into this code, and not just write it like this:

var condition = true;

  while (condition) {
      console.log ("Looped once!");
      condition=false;
  };

I see that 'false' no longer appears in the console after "Looped once!" when using a function, but what exactly is the function doing here?


#2

Which function do you mean?


#3

Sorry! To 'pass' the section the final code looks like this:

var soloLoop = function(){
 
 var condition = true;

  while (condition) {
      console.log ("Looped once!");
      condition=false;
  };
 
};

soloLoop();

Why use the soloLoop function?


#4

If there's a specific reason, I'm not aware of it. You could probably get a definitive answer from the course writer. My best guess would be to get course takers accustomed to syntax of a while loop inside of a function.


#5

why did we use the soloLoop(); at the end do we need it


#6

It's probably just for practicing purpose and unfortunately there are quite a few who would benefit from a review of functions at that point.

About the "false", well the truth is that you're writing your code here in an interactive console. You can test it, run 2+2 and you shall see 4. For bigger chunks of code that means that you'll see the last value of code that is evaluated which is in your case the assignment statement

condition = false;

Now there is one exception (of which I know) and that is the none value of undefined. Now when you wrap your code in a function and use soloLoop() on the last line, the last value is now the value of this function. And the value of a function is the value it returns, so as this function doesn't have a return statement, it means that it's returned value is undefined and as said this value isn't echoed by the console. Hope this explains it a bit.


#7

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