The address for this web page is:   www.crosswinds.net/~fishcaro/day_J8_online_tutorial.htm
On to the next lesson!
Back to the COURSE SYLLABUS

J8. REVIEW TUTORIAL

There is a good web tutorial on JavaScript that will both review and extend the JavaScript that you already know. The tutorial is located at:
http://www.w3schools.com
Click on the link above; then click on Learn JavaScript under the heading Browser Scripting in the left-hand margin. As you work through each section of the tutorial, there is a set of questions and exercises that I want you to do: just click on each link below.

TABLE OF CONTENTS

JS Introduction
JS How To
JS Where To
JS Variables
JS Operators
JS Functions
JS Conditional
JS Looping
JS Guidelines


JS Introduction

  1. What is JavaScript? Who developed it?
  2. What browsers does JavaScript work in?
  3. Before learning JavaScript, what skills should you already have in place?
  4. What is a "scripting lanugage"?
  5. Do you need to purchase a license to use JavaScript?
  6. List four major things that JavaScript can do.
Back to the top!

JS How To

  1. Notice that this tutorial puts the attribute type="text/javascript" in the SCRIPT container, instead of LANGUAGE="JavaScript" which we've been using. Try both ways. Do they both work? Where have you seen the "type=" attribute used before?
    (Actually, the type="text/javascript" should only be used for style sheet information, inside a STYLE container tag. Stick to the LANGUAGE="JavaScript" for your own coding.)
  2. When MUST JavaScript statements end with a semicolon? When is it allowed (but NOT RECOMMENDED) that you can leave off the semicolon at the end of a statement?
  3. How can you hide JavaScript code from older browsers?
  4. Be sure to play with both examples: Write text and Write text with formatting
Back to the top!

JS Where To

  1. When do scripts in the body section execute?
  2. When do scripts in the head section execute?
  3. Where should function scripts go?
  4. Study the Head section example. How can you get something to happen immediately when a page is loaded? What attribute should be used, in what tag?
  5. Write code (without looking at anything!) that defines a function called "message" that brings up an alert box with the message "Have a great day!" This message should be displayed as soon as the page is loaded.
  6. When might you want to use an external JavaScript?
  7. If you write an external JavaScript, what file extension must be used when you save the file?
  8. Should an external JavaScript contain the SCRIPT tag? If not, where does the script tag go?
  9. How do you load an external JavaScript? What attribute should be used, in what tag?
  10. Write an external JavaScript file, open_message.js, that alerts the reader "You are about to have a lot of fun!". Create two HTML documents, test1.htm and test2.htm, and load this external JavaScript into each one.
Back to the top!

JS Variables

  1. What is a "variable"?
  2. What are the two basic rules for variable names?
  3. State two ways that you can create a variable.
  4. To "declare" a variable means to create it, explicitly using the "var" statement.
    Thus, the code
    var x = "declared_variable"
    DECLARES a variable x, but the code
    x = "non_declared_variable"
    does not.
    Be able to answer the question: What does it mean to "declare" a variable?
  5. A GLOBAL VARIABLE is one that is defined everywhere in your Javascript code.
    Be able to answer the question: What is a global variable?
  6. Variables that are DECLARED inside a function are defined only within the body of the function; they are said to be "local variables."
    Be able to answer the question: What is a local variable?
  7. When you DON'T declare a variable inside a function, then it is created as a GLOBAL variable, and may over-write the current value of a variable.
    Study the following code, to see the difference between declaring, and not declaring, a variable inside a function. Given code like this, you MUST be able to predict what will be printed out upon execution!

    First, see what happens when you DON'T declare the variable inside the function:

    <SCRIPT LANGUAGE="JavaScript">
    x = "outside_function";
    document.write("Outside the function, x = ",x,"<BR>");
    function test() {
      x = "inside_function";
      document.write("Inside the function, x = ",x,"<BR>");
    }
    test();
    document.write("After the function, x = ",x,"<BR>");
    </SCRIPT>


    This code will produce the following output:



    Notice that the value assigned INSIDE the function, OVER-WROTE the value assigned OUTSIDE the function. THIS IS NOT GOOD! Usually, you want variables INSIDE a function to be totally separate from those OUTSIDE; you don't want something done inside a function altering what happens outside. THIS IS BAD.

    Now, see what happens when you DO declare the variable inside the function:

    <SCRIPT LANGUAGE="JavaScript">
    x = "outside_function";
    document.write("Outside the function, x = ",x,"<BR>");
    function test() {
      var x = "inside_function";
      document.write("Inside the function, x = ",x,"<BR>");
    }
    test();
    document.write("After the function, x = ",x,"<BR>");
    </SCRIPT>


    This code will produce the following output:


  8. Good rule of thumb: ALWAYS DECLARE VARIABLES INSIDE YOUR FUNCTIONS!
    Be able to answer the questions: "Should you declare variables inside functions? Why or why not?"
  9. Practically speaking, if you ALWAYS use different names for ALL of your variables (both inside and outside of functions), then you'll never have to worry, and you can get away with never declaring any variables. However, good programming technique dictates that you should ALWAYS DECLARE VARIABLES INSIDE YOUR FUNCTIONS! (Notice that I said that one more time, with feeling!)
Back to the top!

JS Operators

  1. Be able to list all the JavaScript Arithmetic operators; Assignment operators; Comparison operators; Logical operators; String operator. For each operator (where applicable) you should know the name (like 'addition') and the symbol used by JavaScript (like +).

    For each operator, be able to give an example that illustrates the use of the operator.
    For example: Arithmetic modulus operator: 10%8 gives the result 0 (why?)

    Note: the string operator '+' is called the concatenation operator. To concatenate means to connect in a series or chain.

  2. INCREMENT and DECREMENT operators:
    There are some operations that are so commonly performed, that shortcuts have been developed to handle them. Often, one has to increase a number by one (increment) or decrease a number by one (decrement).
    x++    is the JavaScript shortcut for  x = x+1 .
    Thus, x++ takes the current value of x, adds one to it, and stores the new number back in x.
    Similarly,   x--    is the JavaScript shortcut for  x = x-1 .

    The increment and decrement operators are frequently used in FOR loops: type this code and study what happens.

    <SCRIPT LANGUAGE="JavaScript">
    for (x=1; x<=10; x++) {
    document.write(x," "); }
    </SCRIPT>

    <SCRIPT LANGUAGE="JavaScript">
    for (x=10; x>=1; x--) {
    document.write(x," "); }
    </SCRIPT>

  3. MORE SHORTCUTS: There are also shortcuts for some common assignment statements:

    In general, the pattern   x blah= y   is a shortcut for   x = x blah y .

    Thus:
    x += y   is a shortcut for   x = x + y .
    x -= y   is a shortcut for   x = x - y .
    x *= y   is a shortcut for   x = x * y .
    x /= y   is a shortcut for   x = x / y .
    x %= y   is a shortcut for   x = x % y .

    Be able to give THREE DIFFERENT ways to take a variable x, add 1 to it, and then store the new value back in x.

    Be able to give shortcuts for each of the following operations:
    x = x+3;
    x = x/3;
    x = x*3;
    x = x-3;
    x = x%3;

  4. A BINARY operator is one that requires two inputs. For example, addition is a binary operator, because two numbers are required for addition.

    A UNARY operator is one that requires only one number. For example, ++ is a unary operator, because a single number is incremented.

    Be able to identify each JavaScript operator as either BINARY or UNARY.

  5. Notice that '+' operates on both NUMBERS and STRINGS.
    Discuss the difference between the following two lines. What will be printed out in each case?
    x = 2 + 3; document.write(x);
    x = '2' + '3'; document.write(x);
Back to the top!

JS Functions

  1. Study the five function examples at the beginning of the lesson. The writer of this code is NOT doing something that I have STRONGLY RECOMMENDED that you do; what is this?
  2. Study the five function examples at the beginning of the lesson. YOU MUST BE ABLE TO WRITE CODE SIMILAR TO EACH OF THESE FUNCTION EXAMPLES, WITHOUT LOOKING: I would give you a description of what I want, and you would write the code. For example, I might say:

    Write a function that creates a button that says "My function". When the button is clicked, your function is called. Your function should bring up an alert message that says "Have a nice day!"

    SO... get out the Simpletext and your favorite browser! Practice writing this code, WITHOUT LOOKING AT ANYTHING! When you can do it two times in a row, from scratch, without looking, then you're ready for class quizzes and tests!

  3. What is an "argument," in the context of JavaScript functions? Can a function have NO arguments? One argument? More than one argument?
  4. If a function doesn't have any arguments, do you still need the parentheses for the function?
  5. WRITE A FUNCTION that prints out the numbers 1, 4, 7, 10, ... Notice that you are starting with 1, and adding 3 each time. You should STOP when the last number is greater than or equal to 200. Put TWO spaces between each number. (Hint: your function should use an appropriate FOR loop. Use an appropriate SHORTCUT assignment statement!)
  6. You're now going to GENERALIZE the previous code. WRITE A FUNCTION that takes three arguments: a START value (like "1" in the problem), an END value (like "200" in the previous problem), and an amount that should be added at each step (like "3" in the previous problem). The function should print out the desired list of numbers.

    Test your function on all these lists:

    5,7,9,...,275
    4,7,10,...,154
    -4,0,4,8,...,140

Back to the top!

JS Conditional

  1. What are "conditional statements," in general?
  2. What are three types of conditional statements that JavaScript offers, and when is it appropriate to use each one?
  3. What is the basic structure of an "If" statement?
  4. Study the "If statement" example. Here, besides getting practice with the "if" statement, you are also being introduced to the way that you can get DATE and TIME information with JavaScript!
    You've seen that numbers and strings can just be typed into a JavaScript program and manipulated. However, object and array values must be CREATED with the "new" operator. This is why you see:
    var d = new Date();
    in the example.
    Once you have a Date object, you can get additional information by invoking the following methods:
    getDate(); returns the day of the month
    getDay(); returns the day of the week
    getFullYear(); returns the year in full four-digit form
    getHours(); returns the hours
    getMinutes(); returns the minutes
    getSeconds(); returns the seconds
    getMonth(); returns the month
    Type the following code to practice manipulating the DATE object! Make sure that you know all these methods, WITHOUT LOOKING!
    var d = new Date();
    document.write(d,"<BR>")
    document.write(d.getDate(),"<BR>")
    document.write(d.getDay(),"<BR>")
    (The days are numbered 0 to 6; which day is 0? What number is Wednesday?)
    document.write(d.getFullYear(),"<BR>")
    document.write(d.getHours(),"<BR>")
    document.write(d.getMinutes(),"<BR>")
    document.write(d.getSeconds(),"<BR>")
    document.write(d.getMonth(),"<BR>")
  5. Write a program that checks the current time/date. If it's Monday, you should print out "Welcome to a new week! It's Monday!"
    If it's afternoon (between 12 and 6) it should say "Hope you're having a good afternoon!"
  6. What is the basic structure of an "If... Else" statement?
  7. Write a program that checks the current time/date. If it's Monday, you should print out "Welcome to a new week! It's Monday!" Otherwise, it should print out "Hope you're enjoying your week!"
    If it's afternoon (between 12 and 6) it should say "Hope you're having a good afternoon!" Otherwise, it should say "Hope you're enjoying your day!"
  8. What is the basic structure of the "Switch" statement?
  9. What is the purpose of "break" in the "Switch" statement?
  10. Use a "switch" statement to do the following:
  11. Study the "Random Link" example. The random method of the Math object is introduced there: "Math.random()"
    Write a FOR or WHILE loop that prints out 50 different calls to Math.random(). Based on your results, determine what "Math.random()" does!
  12. Write code that does the following: randomly select a number between 0 and 1.
    If the number is between 0 and 0.25, print "You get to choose door 1."
    If the number is between 0.25 and 0.5, print "You get to choose door 2."
    If the number is between 0.5 and 0.75, print "You get to choose door 3."
    If the number is between 0.75 and 1, print "You get to choose door 4."
    (You can choose whether .25 gets door 1 or door 2, etc.)
  13. Write code that does the following: randomly print out a WHOLE NUMBER a number between 1 and 100. (Hint: Randomly choose a number between 0 and 1. Multiply by 100. Use the "floor" or "ceiling" method of the Math object, as appropriate.)
  14. Write code that does the following: Randomly print out a WHOLE number between 5 and 75. (Hint: write a linear function that maps [0,1] to [5,75] and use previous ideas.)
  15. Write code that does the following: Create a function that takes two whole numbers as inputs, a start value "s" and an end value "e". Then, it should return a whole number randomly selected between "s" and "e".
  16. A "ternary" operator is one that takes THREE inputs. The conditional operator (?:) is the only JavaScript ternary operator. (Sometimes, it's actually referred to as "the ternary operator." What is the basic structure of the ternary operator?
  17. When you look at the structure:
    (condition) ? value1: value2;
    here's a good thought process: Think: "Is the condition true?" If so, value1 is returned. Otherwise, value2 is returned.
    This returned value can be "captured" in a variable, like this:
    ret = (x==5) ? "five": "not five"
    Or, the returned value can be printed out directly:
    document.write( (x==5) ? "five": "not five" );
  18. Type the following lines of code, to experiment with the ternary operator:
    x = 5;
    document.write( (x==5) ? "five ": "not five " );
    document.write( (x==4) ? "four ": "not four " );
  19. Write code to do each of the following (use the TERNARY operator):
  20. The "if... else if" statement
    Look back at problem #12. You couldn't use the "switch" statement, because you weren't checking for a particular value. You can (and probably did) use multiple "if" statements to accomplish this task. However, this is very inefficient coding, because if the number is (say) between 0 and 0.25, then it definitely WON'T be between 0.25 and 0.5 etc. With multiple "if" statements, JavaScript must look at every "if" statement, and this wastes computer time. A more efficient solution is to use the "if... else if" statement.

    The basic if/else statement is useful for executing TWO pieces of code: one if a statement is true, the other if a statement is false. But when you want to do LOTS of different things, use the structure that is illustrated in the following example:

    if (n<0) {
      // When n is less than zero, do this stuff.
    }
    else if (n>=0 && n<2) {
      // When n is between 0 and 2, do this stuff.
    }
    else if (n>=2 && n<3) {
      // When n is between 2 and 3, do this stuff.  And on and on and on.
    }
     
    Now, re-visit problem #12 (and, a few little twists are being added). Use the "if... else if" structure to do the following: randomly choose a number between 0 and 1, and print it out. If the number is between 0 and 0.4, say "between 0 and 0.4". If it's beween 0.4 and 0.7, say "between 0.4 and 0.7". If it's greater than 0.7, say "greater than 0.7". Then, ask the user if they want to do it again (and proceed accordingly).
Back to the top!







JS Looping


Most of this material is review; the only new statement is "do...while". This is a good review of JavaScript's ability to "loop," i.e., repeat a given segment of code. Since the material is primarily review, there will be some challenging exercises to keep things interesting!
  1. What are the primary three looping statements in JavaScript?
  2. Which looping statement runs through a block of code a specified number of times?
  3. Which looping statement is guaranteed to pass through a block of code at least once?
  4. Which looping statement repeats a section of code while a specified condition is true?
  5. What is the basic structure of the "while" statement?
  6. Typically, a "while" statement gets a variable "initialized" before the loop begins, then this variable is updated inside the body of the statement. Predict the output from this classical "while" statement:
    
    k=1; // initialization
    while (k<=5) { // the code block will be executed while k is less than or equal to 5
    document.write(k,"<BR>");
    k++; // increment k
    }
    
  7. The "do... while" loop behaves much like "while," except that the loop expression is tested at the bottom of the loop rather than at the top, which guarantees that the loop is always executed at least once.
    Compare the output from these two chunks of code to better understand the difference between "do... while" and "while". One of these doesn't print anything at all; the other produces an infinite loop. Determine which is which!
    i=5;
    while (i<5) {
    document.write(i,"<BR>"); i--;
    }
    

    i=5;
    do {
    document.write(i,"<BR>"); i--;
    }
    while (i<5);
    
  8. What is the basic structure of a "for" loop?
  9. Every "while" loop has an equivalent "for" loop; every "for" loop has an equivalent "while" loop. For example, the following two loops are equivalent:
    i=1; // 
    while (i<=5) {
    document.write(i,"<BR>");
    i++;
    }
    
    for (i=1; i<=5; i++) {
    document.write(i,"<BR>");
    }
    
    Which is more compact? Mostly, it is just personal preference that dictates whether someone codes with "while" or "for".
  10. Write code for each of the following using BOTH "while" and "for":
  11. Study the "looping through HTML headers" example. Mimick the idea there, to do the following:
    Prompt for a name. Then print it out in sizes 1 through 7, like this:

    Hint: The following JavaScript code prints the specified string in size 3:
    string = "Carol";
    document.write(string.fontsize(3));
    

    Precisely, "fontsize()" is a method of a string object; in the parentheses, you specify the desired fontsize (between 1 and 7).
Back to the top!







JS Guidelines


Be sure that you can answer the following questions!
  1. What does "case sensitive" mean? Is JavaScript case sensitive?
  2. How does JavaScript handle extra spaces? In particular, will all of the following lines of code assign a value of 5 to x? If not, cross off the ones that will NOT work.
    x = 5;
    x=5;
    x=  5;
  3. We've run into trouble breaking lines inside quotes in our document.write statements. This section of the tutorial has the answer to our woes! What is the solution?
  4. One of the following is a backslash, and one is a forward slash. Which is which?
    /    \
  5. How can you insert special characters (like ", ', and &) inside a string?
  6. This tutorial reviews one way to make a single-line comment in JavaScript. What is it?
  7. This tutorial reviews a way to make a multi-line comment in JavaScript. What is it?
The next lesson (J9. JavaScript References) will provide us with some of the nitty-gritty details of the JavaScript language!

Back to the top!







On to the next lesson!
Back to the COURSE SYLLABUS
© 2001 Carol J.V. Fisher    All Rights Reserved