Session 15: A Guided First Tour of JavaScript

On to JavaScript

We begin to learn JavaScript. After completing this unit, we will be able to write code to interact with HTML and CSS. Given time, a secondary goal is that will be able to we write code to do basic data processing tasks that web developers face.

Our main goal essentially requires knowing JavaScript. Here is a comment from David Heinemeier Hansson, the creator of the popular web framework Ruby on Rails, in a blog post about another language for client-side scripting:

... you still have to accept the fact that running code in the browser means running JavaScript.

Using any language other than JavaScript requires extra tooling and other hoops to jump through.

One way that we will use JavaScript is to let the user interact with the page, as illustrated last session in different ways to style and display footnotes within a page.

Another is to create dynamic pages. Consider the Pi Clock, which shows the time in hours, minutes, and seconds using the pairs of digits that occur in the first 100,000 digits of pi. This page changes with no interaction from the user, thanks to JavaScript.

for more information The creator of the Pi Clock tells its story on this page. We can even download HTML, CSS, and JavaScript for the page from GitHub.

JavaScript is powerful enough to help us achieve the second goal as well. The HTML table on this page can serve as a motivation. This table can be generated from this dataset the Social Security Administration makes available, or from the data we get by copying the text on the page. Knowing JavaScript will empower us to process a text file and generate HTML for our web pages.

Today, we'll learn some of the atomic building blocks of JavaScript, some of the ways to build bigger expressions out of smaller ones, and how to use expressions to construct sequences of actions.

Fire up the JavaScript console in your favorite browser. Let's learn a new language!

Primitive Expressions: Literal Values

A JavaScript expression is any code that evaluates to a single value. The simplest expression is a literal: an expression that evaluates to itself.

> 42                    // a number
42
> 42.5                  // decimals, too
42.5
> -8                    // negative numbers
-8
> 42.0                  // JS simplifies numbers when it can
42
> 'Eugene'              // a string: a sequence of characters
'Eugene'
> 'tralfamadore'        // upper- and lowercase
'tralfamadore'
> 'Hello, world!'       // can contain spaces and other characters, too
'Northern Iowa'
> '• ¶ § ©'             // lots of other characters: opt-8,7,6,g
'• ¶ § ©'
> "Eugene"              // we can use double-quotes, too

We will use strings and numbers often.

Compound Expressions: Using Operators

We can combine two or more expressions into a compound expression in a number of ways. The simplest is by using an operator:

  > 42 + 14               // the usual arithmetic
  56
  > 3 * (4 + 4)           // we can combine compound expressions, too
  24
  > 7 / 3                 // does its best with non-terminating numbers
  2.3333333333333335
  > 7 % 3                 // and some math-y operators (remainder)
  1
  > - 8                   // some operators take only one argument
  -8
  
  > 'Eugene' + 'Wallingford'     // + "concatenates" strings
  'EugeneWallingford'
  
  > 10 / 2
  5
  > '10 / 2'              // strings are literals -- not evaluated
  '10 / 2'
  > '10' + '/' + '2'
  '10/2'
  

Practice Exercises

Write an expression to find how many days are left in 2023 by summing the days left in October, November, and December.

Write an expression to assemble a person's name in "last, first" form by concatenating strings for their first and last names.

Comparisons and Boolean Values

JavaScript also has operators to compare things:

  > 42 > 14               // greater than?
  true
  > 1 > 14
  false
  > 42 < 14               // less than?
  false
  > 8 === 8               // equal to?
  true
  > 8 === 8.0
  true
  > 27 !== 13             // not equal to?
  true
  > 27 !== 27
  false
  > true                  // literal true
  true
  > false                 // literal false
  false
  > true === 'true'       // these are different from strings
  false
  

These operators show us a new kind of value: Booleans. There are only two Boolean values: true and false. Notice that these values do not use quotation marks. They are keywords. Boolean values will be useful when we have to make choices such as Do this or do that? or Do this again?

JavaScript has other equality operators that we will encounter later. We will use === and !== unless we must use something else.

Primitive Expressions: Named Values

A second kind of primitive expression is the named value, what programmers usually call a variable.

To create a name, we use the keyword let to write a JavaScript statement:

  > let firstName = 'Eugene';     // create firstName and give it 'Eugene'
  undefined                          // statements are not expressions!
  > firstName                     // what is the value of firstName?
  'Eugene'
  
  > let lastName;                 // we can create a name without a value
  undefined
  > lastName = 'Wallingford';     // then give it a value
  'Wallingford'
  

Up to this point, wee had seen numbers, strings, and boolean values. This interaction shows us undefined, which is a special value all its own. undefined means that a name has never been given a value.

  > let b;
  undefined
  > b
  undefined
  
Naming Rules

In JavaScript, a variable name must start with a letter (a-z or A-z), an underscore (_), or a dollar sign ($). Subsequent characters can be letters, numbers, or underscores. However, we cannot use one of JavaScript's keywords, such as true, false, or let, as the name of a variable.

For example, $31 and _private are valid names, but 1abc and aName% are not.

Otherwise, we can use any string of characters we want. If a variable name consists of more than one word (example: lastName), we use camel case to make the name more readable.

JavaScript names are case-sensitive: lastName and lastname are different variables.

One final note for now: If we don't use let or the semicolon, the interpreter will accept our code, but it may not treat the expression as we intend. (We may discuss this issue in more detail later in the course.) We will use them as a matter of good practice.

Assignment Statements

The = operator can also change the value of an existing name:

> firstName = 'Tua';            // the = operator can also change
'Tua'                           // the value of an existing name

We call code of the form [name] = [expression]; an assignment statement. It means "let [name] take the value of [expression]".

Note that this is a single equal sign, unlike the equality operators. In JavaScript, the equal sign does not mean what it means in mathematics. In math, a = b means "a equals b". In JavaScript, it means to compute the value of b and copy it into a. It is an instruction to make a equal to b.

An assignment statement changes only the value of the name on the left hand side.

Practice Exercise: Work through each line of this chart. Enter the statement in Column 1, then check the value of a and b by entering them at the prompt before moving on to the next line.

a table with a sequence of assignment statements and values of a and b

Did any of the results surprise you?

Statements

If all we could do was compute the values of expressions, we'd feel limited. We'd like to take actions, such as modifying a web page.

We have already seen one of the simplest actions: assigning a value to a name. There are different types of statements, some of which we will learn about in the coming weeks.

A sequence of such actions can accomplish something bigger than a single action. That is all a program is, a sequence of such actions that perform a specific task.

For example, here is a sequence of statements to compute the area of a circle:

let pi = 3.14159;                         // pi is a number 
let radius = 4.2;                         // radius is a number
let area = pi * radius * radius;          // calculate area from radius

"Area = " + area;                         // evaluate the area in the console

Practice Exercises

Write a sequence of assignment statements to assemble your full name from variables that equal your first, middle, and last names.

Using the JavaScript console is a wonderful way to experiment with single expressions and statements. Working with a sequence of statements such as the code for a circle's area exposes a weakness. The statements are separated and don't look or feel like a unit. It would be handy if they could be stored in a text file like our CSS style sheets.

Our editor for HTML and CSS, VS Code, works just as well for JavaScript. It color codes the text and offers autocompletion to save us time (and remind us of names). All it needs is a way to execute the JavaScript code. node.js, a standalone version of the JavaScript engine that drives Google Chrome, can be that tool.

Closing

I've graded Homework 6. I was impressed by the pages you built, and by the way some of you ued the assignment to practice so many techniques. Congratulations. I hope to have the midterm exam graded by next time.

There is no homework assignment outstanding for this week. If you did not submit Homework 6 and would like to, let me know soon.

See these instructions for installing node.js on your computer.