Why do you need the function?


#1

The exercise uses this code:

var thing = true;

var soloLoop = function(){
while(thing){
console.log("Looped once!");
thing = false;
}
};

soloLoop();

However, this does the same thing, with less code:

var thing = true;

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


So why do you need the function at all?


#2

You want to be able to break large code into chunks. This isn't a long piece of code, but they want to introduce you to functions. A big part of code is writing functions, but then you control when you call them and when they work with other functions as well.
I hope this makes some sense. It's hard to see why functions are needed, but the more you study them, the more you'll realize that they're a big part of programming, especially if you're going to do it as a career.


#3

There is nowhere in the lesson that says while loops should be nested in the function, pay attention to the function_name, it is very much relevant to what the loop is doing. It is just to give you a better understanding of the process that is happening. :slight_smile:


#4

Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure - a set of statements that performs a task or calculates a value. Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function.

In other words, JavaScript function is a block of code designed to perform a particular task. A JavaScript function is executed when we call it. I mean, that function contains reusable code which can be called anywhere in your program. This eliminates the need of writing the same code again and again. It helps programmers in writing modular codes. Functions allow a programmer to divide a big program into a number of small and manageable functions.

So, now if you need to use your while loop many times you just need to call your function soloLoop(). Hope this help you.

UPDATED.

Look to "Why Functions?"


#5

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