To begin, let's finish up the last example from Javascript Exercise #3: Loops & Conditionals.
Let's also bring back the printVar() function:
We already covered the basics on functions in javascript in Javascript Exercise #2: Variables & Arrays, so in this exercise, we will cover a few more important features of functions, and then I will give you a couple of exercises for you to work on during the remainder of class.
One thing to be aware of when using functions is scoping constraints. Consider the following example:
Notice how a and b both changed their values within the function, but not outside of it after the function ran. But notice how c changed its value permanently. Because c was not declared within the function as a variable, the function found the global variable c, and changed its value, instead of creating a local variable c which could be manipulated internally.
Another thing to be aware of about functions, is the idea of recursion. Recursion happens when a function calls itself. Consider the following example:
As with while loops, it is very easy to create infinite loops with recursion. If your if statement is incorrect, you may create a condition where the function never stops calling itself. Many computer scientists idealize recursion as a method of creating functionality. In fact, there are languages such as scheme which do not have looping mechanisms: all looping must be performed via recursive function calls. However, I'm not convinced that recursion is qualitatively better in any way. Sometimes the code is cleaner, though that doesn't always make it easier to read. There may be performance issues which I am unaware of. But aside from that, I can't see any reasons personally to choose recursion over looping, in situations when both can be used. Thus, use the method which makes the most sense to you, given your task.
Below is a short list of javascript exercises. Please select one or more that seem interesting to you and work on them for the remainder of class.