JavaScript   Class Activities for Intro to JavaScript

JavaScript

JavaScript gives web pages real power. It transforms a passive, static page that you can read into an active, dynamic application you can interact with, such as Gmail, Facebook, and many more.

Consequently, it's difficult. Any first programming language is, but all programming languages bear many similarities, so learning part of one will help you immensely in learning your second.

We won't become experts in JS, but we'll learn a lot of the fundamental ideas behind all programming languages, such as:

  • datatypes to represent information
  • variables to store information (data)
  • functions to transform the data
  • functions to allow modularity, abstraction, reusability and a host of other important features.

Recap of the Most Important Ideas in the Reading

  • Variables are named storage locations that store values. Think of them like labeled boxes. (They live in RAM, in our computer organization picture.)
  • Here's an example of two assignment statements.
    var price = 5.99;
    var x = 100;
  • The value assigned can be an expression, like this:
    var total_price = (price - discount) * (1 + tax_rate);
  • Values can be numbers or strings. Strings are sequences of Unicode characters.
    var item_name = "Fizzing Whizbee";
  • For numbers, all the usual arithmetic operators work:
    var z = (3*x+1)/2;
  • There's one new operator you probably aren't familiar with, the remainder operator. The following calculation can be used to compute the day of the week five days from x. (We'll learn more about dates later.)
    var y = (x+5)%7;
  • String literals are defined with quotation marks, either single or double
    var fname = "Harry";
    var lname = 'Potter';
    var name2 = "O'Malley";  // can't use single quotes here
    var quote = "Hermione said, 'Wingardium LeviOsa'"; // need double quotes here
    
  • The main operator on strings is concatenation, like this. (Any problem here?)
    var fname = "Harry";
    var lname = "Potter";
    var whole_name = fname + lname;
    

Some useful functions

  • The alert() function pops up a window with some text:
    alert("Butterbeer costs ");
  • The console.log() function writes some text into the console, which is hidden from muggles:
    console.log("Madame Rosmerta waters the butterbeer");
  • The prompt() function pops up a box to ask for a string and returns the string:
    var pass = prompt("what is the password for Gryffindor tower?");
  • The prompt() function can have a default value:
    var pass = prompt("what is the password for Gryffindor?","caput draconis");
  • The parseInt() function converts a string of digits to a number:
    var how_many = prompt("how many butterbeers?");
    var n = parseInt(how_many);
    alert(n+" butterbeers!");
  • The parseFloat() function does the same thing, but for non-integers:
    var price = prompt("what price?","8.99");

Quiz Question Nr. 1

Where can we place JavaScript code?

  1. inline, using special tag attributes

  2. in the document, using the <script> tag

  3. in an external file, using the <script> tag

  4. all of the above

Quiz Question Nr. 2

How can we put comments in JavaScript code?

  1. double slashes like this: // tricky

  2. slash star like this: /* tricky */ tag

  3. angle brackets like this: <!-- tricky --> tag

  4. none of the above

Quiz Question Nr. 3

What's wrong with the following code?

5.99 x 1.62 = price-with-tax
  1. assignment in the wrong order

  2. variable name has wrong syntax

  3. incorrect operator used

  4. all of the above

Quiz Question Nr. 4

What's wrong with the following code?

var long_quote = "Now is the winter of our discontent
made glorious summer by this son of York";
  1. Wrong quotation marks

  2. underscore in variable name is incorrect

  3. line break in string literal is not allowed.

  4. nothing; the code is fine

Quiz Question Nr. 5

Explain the following code. Predict what it will do if someone types in 18.

var age = prompt("Enter your age ");
var next = age + 1;
alert("On your next birthday, you'll be "+next);
  1. It gets an error

  2. It displays "18"

  3. It displays "19"

  4. It displays "181"

Quiz Question Nr. 6

Now, run the code. Explain its behavior.


  1. The plus sign means addition

  2. The plus sign means concatenation

  3. The code does the wrong thing

  4. The code stores something in the variable age, then creates a variable next and assigns in age+1, then does an alert with a string and the variable next

The JavaScript Console

We can use the Chrome Inspector and switch to the JavaScript console to see error messages and even type in code to try. Let's do that together. Command-option-I on a Mac will open the JavaScript Console.

JS Exercise

Imagine we want to use JavaScript to compute the height of a tree after some number of years after we buy it. We buy it as a sapling that is 6 feet high, and the nursery predicts that the tree will grow 2 feet per year. This is a situation where we can use the y = mx + b linear functions we learned in high school. For example, if the user wants to know how tall the tree will be in 10 years, we would tell them that the predicted height is 26 feet. (The numbers are simple enough that you can check your code by doing the arithmetic in your head.)

  1. Draft some code to solve this computation for us. You'll use prompt to ask the user for the number of years into the future they want to know about. You'll use alert to tell them the predicted height.
  2. If you'd like, compare your code with a neighbor and discuss any differences.
  3. Open the JS console and try your code there. (Alternatively, go to jsfiddle.net to start a JS fiddle. You'll only need the lower left pane (the JavaScript pane). However, JS fiddle doesn't show you error messages as immediately as the JS console.)
  4. Type your code into the JS console. Each line will get computed in turn.
  5. For extra credit, have your alert look like this:

    in 10 years, the tree will be 26 feet

    That is, it should report the input and the output, along with some nice descriptive text.

Solutions

Will be posted later, visit again after .

For the quiz questions:

          1. D. All of them are okay.
          2. A or B but not C
          3. D. All of the above
          4. C. Line breaks aren't allowed.
          5. D.  It displays "181"
          6. B.  The plus sign means concatenation (in this code).
        

Here's the solution to the JS Fiddle activity.

var height0 = 6;
var slope = 2;
var years = prompt("how many years?");
var height = slope*years + height0;
alert("in "+years+" years, it will be "+height+" feet high");

© Wellesley College Computer Science Staff. This work is licensed under a Creative Commons License. Date Modified: Wednesday, 05-Oct-2016 20:21:19 EDT