Wednesday, October 15, 2014

Advanced JavaScript Lesson 01


Advanced JavaScript Tutorial – Lesson 1


Contents
  1. An If-Then-Else Shortcut
  2. What Is This Thing Called Var?
  3. The Way of Var
  4. Conclusion

An If-Then-Else Shortcut

One of the most commonly used statements in JavaScript is the good old if-then-else. Take the Webmonkey reward schedule for instance:
01if (monkey_behavior == "good")
02
03{
04
05   var toy = "videogames";
06
07else {
08
09   var toy = "rocks";
10
11
12
13}
In plain English, this means, “If the monkey’s been good, he gets to play videogames. If not, he gets only rocks.” For reasons of legibility, it is a perfectly good way to do this. For those who don’t like to squander keystrokes, however, there is a shortcut (albeit, a less legible one). It’s called the “conditional operator,” and it goes a little something like this:
1var toy = (monkey_behavior=="good") ? "videogames" :"rocks";
This expression does the same thing as the if-then-else statement above it. See what I mean about legibility? The conditional operator has three parts:a conditional test, a value to return if that test is true, and a value to return if that test is false. So, in the above example, the conditional test is (monkey_behavior=="good"). If that test is true, it returns the value after the question mark. In this case, it’s the string videogames. If the conditional test is false, the value after the colon is returned; in this case, it’s rocks.
This sort of shortcut is most useful inside function calls. For example, you can use it to do something like this:
1var password = "open sesame";
2
3var answer = prompt("what's the password? ","");
4
5alert((answer == password) ? "welcome!" :"buzz off");
Click here to see this in action. What you’re seeing is the conditional operator doing its job and returning either welcome or buzz off, depending on the answer you give at the prompt. The value returned by the conditional gets sent to alert, which throws up an alert box with that value.
Without the conditional operator, the code would look like this:
01var password = "open sesame";
02
03var answer = prompt("what's the password? ","");
04
05if (answer == password)
06
07{
08
09   alert("welcome");
10
11else {
12
13   alert("buzz off");
14
15}
It’s definitely longer, but some people find it more readable, and understandable, to actually write out the if-then-else statement. The method you choose is simply a matter of personal preference.
OK, last stop on today’s tour of loose ends: the mysterious var.

What Is This Thing Called Var?

Way back in Part I, Day 2, I said that the first time you use a variable, you should declare it with the word “var.” I promised that I’d explain why when I talked about functions. Well, I forgot! So, now is the time.
Just to jiggle your memory, here’s an example of var in use:
1var happiness = "a banana split";
2
3alert("The monkeys think happiness is " + happiness);
This little blurb declares a variable called happiness, then throws up an alert box that uses that variable.
If you’ve been looking at other people’s JavaScript, you might have noticed that not everyone declares their variables with var, which can cause problems. First, some versions of MSIE will bomb, or at least act strangely, if a variable isn’t declared with var. This is especially true for MSIE on Macs. Second, if you want to write JavaScripts of any significant size, you’re going to have to write your own functions. And once you start writing your own functions, you really need to understand what var is all about.
As described in Part I, Day 4, a function is a block of JavaScript that can be called when necessary. The best functions are self-contained. You know what goes into the function and what comes out of it, and, once you’ve written the function, you don’t have to worry about how it works.
As long as all your functions are self-contained, you never have to worry that writing a new function will accidentally screw up a function you’ve already written. The key to writing self-contained functions is to make sure that your function doesn’t alter variables that aren’t passed directly into them as parameters.
Here’s an example of what can happen if you’re not careful. Let’s say you want to write a program that converts Fahrenheit temperatures into Celsius. Click the Fahrenheit/Celsius converter to see what I mean. If you convert 50 degrees Fahrenheit, you get a message saying, “50 degrees Fahrenheit is 10 degrees Celsius.” You could write a script without vars that would look something like this:
01function fahrenToCelsius(faren)
02
03{
04
05    temp = (faren - 32) * 5/9;
06
07    return temp;
08
09}
10
11function convertTemp()
12
13{
14
15    temp = prompt("what temperature fahrenheit? ","50");
16
17    celsius = fahrenToCelsius(temp);
18
19    alert(temp + " degrees Fahrenheit is " +
20
21    celsius + " degrees Celsius.");
22
23}
The workings of these functions should be pretty clear to you. One function named convertTemp() calls another function named fahrenToCelsius() and returns the results. Take a moment to make sure you understand what’s going on. Breathe. Breathe. If it’s just not coming to you, revisit Day 4, which covers functions at great length.
OK, ready?
The confusing thing about this example is that the variable called temp is used in both functions. In the convertTemp() function, it’s used to store the temperature in Fahrenheit (which is supplied by the user). In the fahrenToCelsius() function, it’s used to calculate temperature in Celsius. Not only does this confuse us, it also confuses JavaScript. Here’s what happens when you try running the code without vars.
Notice that if you try to convert 50 degrees Fahrenheit, you get a message that says, “10 degrees Fahrenheit is 10 degrees Celsius.” Why does the program suddenly think you entered 10 degrees instead of 50? Let’s trace the functions to see what happened.
When we call convertTemp() and type “50″ into the prompt, we get
1temp = 50;
In the next step, “temp” is passed to the function called farenToCelsius(). Inside farenToCelsius(), the parameter called faren is then set to 50 and “temp” gets set to (50 – 32) * 5/9, which is 10. Before returning the value, you have:
1faren = 50
2
3temp = 10
Now farenToCelsius() returns 10 to the variable celsius:
1temp = 10
2
3celsius = 10
And we’re left with the false statement, “10 degrees Fahrenheit is 10 degrees Celsius.”
It’s possible to solve this issue if you carefully avoid naming your variables the same thing. If you didn’t have a variable called temp in both functions, you wouldn’t have a problem.
Unfortunately, this isn’t the best solution. As you start adding more and more functions to your script, it becomes harder to ensure that you’re not re-using variable names. Also, you will repeatedly use lots of variable names, like loop, index, count, and the_name. Coming up with different versions of these commonly used variable names would be a real pain.
A better solution is to tell JavaScript that the variable called temp inside the fahrenToCelsius() function is different from the temp variable in the convertTemp() function. If every function has its own special temp variable, then you don’t have to worry about certain functions messing with the variables of other functions.
If you haven’t guessed yet, this is exactly what var does. Let’s take a look.

The Way of Var

To keep JavaScript from mixing up same-name variables, put var in front of your variables as you declare them. A variable inside a function that’s declared with var is called a local variable, and it only exists inside that function. In general, you want your variables to be local whenever possible.
Here is the JavaScript with the correct vars in it:
01function fahrenToCelsius(faren)
02
03{
04
05   var temp = (faren - 32) * 5 / 9;
06
07   return temp;
08
09}
10
11
12
13function convertTemp()
14
15{
16
17   var temp = prompt("what temperature Fahrenheit? ","50");
18
19   var celsius = badFahrenToCelsius(temp);
20
21   alert(temp + " degrees Fahrenheit is " +
22
23   celsius + " degrees Celsius.");
24
25}
And here’s how it works. Let’s say we call convertTemp() and type 50 into the prompt. Because we used var before the prompt, this temp is localized to the convertTemp() function. So …
1(inside convertTemp) temp = 50
As before, we pass temp to the function called fahrenToCelsius(). Inside fahrenToCelsius(), the parameter called faren gets set to 50. Then temp is set with the line:
1var temp = (faren - 32) * 5 / 9;
As before, putting that var in front of temp tells JavaScript, “This variable called temp is different than any other variable called temp. This one exists only inside the fahrenToCelsius function.” Once JavaScript finishes with fahrenToCelsius(), the special temp variable vanishes. So, just before fahrenToCelsius() returns,
1faren = 50
2
3(inside fahrenToCelsius) temp = 10
4
5(inside convertTemp) temp = 50
fahrenToCelsius() then returns its version of the temp variable, which is 10. Once we leave fahrenToCelsius(), its version of the temp variable vanishes.
When fahrenToCelsius() returns, it sets the variable called celsius to 10:
1(inside convertTemp) temp = 50
2
3
4
5(inside convertTemp) celsius = 10
And thus the alert message says, “50 degrees Fahrenheit is 10 degrees Celsius.” Which is exactly what we want.
To review, by using var before a variable, you localize that variable to the one function that houses it. And once that function ends, the variable ceases to exist.
And that’s the (loose) end of today’s lesson. Now all that’s left is your homework assignment.

Conclusion

I didn’t want to give you anything too heavy on the very first day. Mostly I just wanted to make sure you understood all the elements covered in Part I. After today, we’ll be diving in pretty deep, and, if you don’t have a firm grasp of the basics, you might slide into an abyss of confusion. Or – even worse – stop reading. So, make double-sure you understood:

  • why var is a good thing;
  • how to use the if-then-else shorthand operator.

No comments:

Post a Comment