LIS 390W1A - Lab 17: More Functions

Legend

 
= Javascript
 
= PHP

Brief Review

  • "What is a strongly typed language (differences from a regular one), and what are it's advantages, disadvantages, and best uses?"

  • "What is a cookie? What do you use that for?"
  • "When using Javascript, do you memorize the coding?"
  • What is the difference between javascript and HTML? How do you choose which to use when creating content in your website?

Javascript Functions - More Advanced

We already covered the basics on functions in javascript in Lab 15: Variables, Arrays & Basic Functions, 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.

To work our examples, let's bring back the printVar() function:

Scoping in Javascript

First, let's go back to the javascript exercise in Lab 15 and correct an error I made.

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.

Javascript Recursion

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.

PHP Scoping & Recursion

PHP also has scoping and recursion. Recursion works the same as in javascript. Scoping is a bit different. Click on the link and we will review scoping for PHP.

Nothing to Turn In

There is nothing to turn in for this lab. Keep working on Lab 16 and your Personal Website Assignment.