[programmingbasics] Programming Basics : Lesson 3, Fundamentals (B)

  • From: Bryan Prusha <bryanprusha@xxxxxx>
  • To: programmingbasics@xxxxxxxxxxxxx
  • Date: Sat, 23 Oct 2010 18:03:30 -0700

Concepts : variables and statements or "A little middle school math never hurt 
anyone"

Doing math on the computer has limited functionality if there isn't a way to 
hold on to that information and perform yet more work on it later (like more 
math or comparing a result to other values). This is where the concept of a 
variable comes in. Yes, variables, those hated x's, y's and z's from algebra. 
The simplest way to think of a variable is as a small piece of scratch paper on 
which you scribble a phone number, address or shopping list tally. Accordingly, 
variables can be named in convenient ways like 'thePhoneNumber', 'myAddress' or 
'shoppingSum' so we can easily remember what they are, what they're for and 
what to do with them.* Variables can be initialized to one value, set to 
another and later ignored and forgotten when no longer necessary. "Underneath 
the covers" variables are references to a small chunk of computer memory, big 
enough to hold the information you're putting into it, the computational 
equivalent of a piece of scratch paper. Modern programming languages allocate 
this memory, hold onto it while you're using it and clean it up when you're 
done, automatically. Now that we can perform a series of operations there needs 
to be a way to separate each operation from the next. Generally, each operation 
is placed on a separate line in the file. In English a sentence often contains 
a noun, verb, direct object and a period at the end. This separates each 
completed thought, or expression, from the next. In programming statements, 
variables and values (eg. 12345) behave like nouns and direct objects. Logic, 
math or comparison operators behave like verbs. Statement separators, like a 
semicolon, and a new line act like the period at the end of a sentence. Compare 
the structure of the following English sentences with their programming 
equivalents.

        Find some scratch paper and write the number 2 on it. Add 5 to the 
number and write that result on the scratch paper erasing the first value. Say 
out loud whether the resulting value is equivalent to 7.

        var scratch = 2;
        scratch = scratch + 5;
        alert( scratch == 7 );

*Giving variables names like "thePhoneNumber" where multiple, capitalized words 
are mushed together (often with the first letter in lower case) is another 
computer science tradition called Camel Caps, 
http://en.wikipedia.org/wiki/Camel_caps.

JavaScript : Statements

Now that we've covered the basics of variables and statements let's look at how 
these concepts play out in JavaScript. The following is a list of the concepts 
we discussed above and how they look in JavaScript. Each concept is named, 
given an example expression and what the expression evaluates to (after the 
->). Comments are a method of documenting your code. They are indispensable 
during the design process and help you remember why you did what you did when 
you have to identify a bug in that code years later. Comment early. Comment 
often. Finally, JavaScript supports two special values of similar but slightly 
different meaning, "null" and "undefined". By default, a variable has the value 
"undefined" when created. "null" is often used to set an "empty" value to a 
variable to show that it has been explicitly defined to contain nothing. This 
is useful to test the validity of a variable that your program doesn't always 
use to contain specific value.
        
        statements
        ;       semicolon                       ends a statement
        var     variable                        var foo;                        
-> declare the variable foo
        =       assignment              foo = 8;                        -> 
assign the value of 8 to the variable foo
        //      comment                 everything after the '//' on that line 
has no effect on the program
        /* */   comment                 everything between '/*' and '*/' has no 
effect on the program
        null                                    an empty value
        undefined                               an unassigned value

This list contains math shorthand operators. They are convenient forms of the 
math operators described in Lesson 2 that may be used to modify the value 
contained in a variable.
        
        math shorthand operators
        ++      increment                       foo++;                  -> foo 
= foo + 1;
        --      decrement                       foo--;                          
-> foo = foo - 1;
        +=      add in place            foo += 3;                       -> foo 
= foo + 3;
        -=      subtract in place               foo -= 2;                       
-> foo = foo - 2;
        *=      multiply in place               foo *= 2;                       
-> foo = foo * 2;
        /=      divide in place         foo /= 2;                       -> foo 
= foo / 2;
        %=      modulo in place         foo %= 2;                       -> foo 
= foo % 2;
        
Examples & Suggestions : Knock it up a notch… BAM!

Because JavaScript is primarily used as a way to make web pages more active I 
need to go over just a few bits of HTML (the language of web pages) to proceed. 
The following is a bare bones web page whose sole job is to execute the 
enclosed JavaScript code in a browser. The <script> tag tells the web browser 
there's JavaScript code embedded in the HTML. In the JavaScript section of the 
file I've added a small bit of code that updates the content of the web page 
with a log of your program's output. The expression "printf( value )" behaves 
like the expression "alert( value )" that we'e used in earlier lessons except 
that instead of showing your program's output in an alert window it shows it as 
a running log in the web page like an old fashioned ticker tape calculator. 
We'll talk more about how "print()" actually works in a future lesson. For now, 
just trust me that it works.

<html>
<body id="body">
</body>
<script type="application/x-javascript">

// print( value ) logs your program's output to the web page
function print( value ) { document.body.innerHTML += value + "<br>"; };

// your JavaScript code goes here

</script>
</html>

Create a new, plain text document in your text editor, copy and paste the above 
HTML code to the new document and save it with the name "Test.html". From now 
on we'll run our Examples & Suggestions code from the Test.html file rather 
than from the URL field of the browser. Note, when creating a plain text file 
in TextEdit on MacOS X, choose File->New and when the document appears chose 
Format->Make Plain Text. When opening the file for editing make sure to check 
the "Ignore rich text commands" check box in the File->Open… dialog box. This 
forces TextEdit to load the file as plain text that you can modify rather than 
attempting to uselessly render the HTML as a website. Windows users may need to 
perform a similar actions in their editors as well.

Try this example list of operations by copying and pasting it into the "// your 
JavaScript code goes here" section of Test.html. Double click the file to load 
the web page and run the program in your browser. Play with the example. Create 
new variables, assign values to them and try out some of the new shorthand 
operations. After making changes, be sure to reload Test.html in the browser to 
see the new results. Now we're writing programs with an ordered set of 
instructions like our original recipe example. Computers are designed to excel 
at performing long, tedious list of instructions so we don't have to.


/*      Code Begins Here
        
        This is a span of comments just for example.
        Nothing between the slash-asterisk and asterisk-slash has any effect on 
the behavior of the program.
        It's only here so it can be read with the code.
*/

// with single line comments, everything before the "//" must be a valid 
expression, everything on the rest of the line has no effect on the program 

var someBeans;                                  // create a new variable named 
someBeans

print( someBeans );                             // undefined, someBeans is a 
new variable that has not been set yet

someBeans = 5;                                  // assign the value 5 to 
someBeans

var moreBeans = 7;                              // create another variable 
moreBeans and immediately initialize it to the value 7

var beanCount = someBeans + moreBeans;  // the sum of beans, variables holding 
numeric values can be treated just like numbers

print( beanCount );                             // show me the money!

beanCount--;                                    // remove a bean, maybe it had 
a worm

print( beanCount );                             // view the updated value

alert( "Pause" );                                       // our old friend alert 
will stop the flow of the program, see the rest of the logging appear after 
pressing OK

print( beanCount / 3 );                         // how many beans would each 
person get when dividing the remaining beans evenly between 3 people?

beanCount %= 3;                         // update beanCount with whatever 
remains after divvying up only whole beans

var doBeansRemain = beanCount > 0;      // are there beans leftover?, variables 
can hold the result of operations on other variables and values

print( doBeansRemain );                 // doBeansRemain == true

doBeansRemain = "ohyeahyoubetcha"; // variables may even be reassigned from one 
type of value to another, this can have specific applications

print( doBeansRemain );                 // interesting, print() can work with 
lots of different value types too

doBeansRemain = null;                   // set doBeansRemain to a null clearing 
out its value when we're done so we won't think it's valid later

print( doBeansRemain );                 // is doBeansRemain valid now?, nope

/*      Code Ends Here          */


Note that misspelling a variable or entering an invalid statement or operation 
may cause the program to stop part way through because the browser found an 
error in the code. Safari includes some nice developer tools built right into 
the browser that are indispensable when tracking down this kind of issue. If 
you're a Safari user, try navigating to the Advanced Preference Tab 
(Safari->Preferences…), check the "Show Develop menu in menu bar" option and 
choose Develop->Show Error Console in the new menu in the menubar. Try adding 
an error to your code (eg. "print( blah )" where blah is not a variable you've 
declared in Test.html) and reload. You'll see the console provide an error 
description and the line number of the error in the file like the following.

"ReferenceError: Can't find variable: blah                      Test.html:27"

Coming up next, Conditionals or "I'm the decider".

Other related posts:

  • » [programmingbasics] Programming Basics : Lesson 3, Fundamentals (B) - Bryan Prusha