CSE 154

Lecture 5: JavaScript

Today's Agenda

Reminders

(Brief) Notes on Lecture

Example Quiz Question

CSS Recap

JavaScript

Reminders

HW1 is out now, due next week. Assessment on HTML and CSS.

CP1 was due last night, can still be turned in late until Thursday night.

OH and WPL available for questions. Check the calendar for times, Ed for Zoom links.

Quiz 1 will release at 3:00pm after lecture today. Will be available for 24 hours.

Note on today's lecture

We'll be spending a lot of time in Chrome and in Chrome's DevTools.

Slides are here largely for reference.

Wrapping Up Module 1

Summary of Flex Layout

Flex is a powerful way to create responsive page layouts

Really takes practice, but remember to use sketches, the DOM, and the inspector!

Making an element a flex parent will unlock various flex properties to distribute across an axis and align down that axis.

Common bugs:

  1. Setting display: flex on children instead of parent: Remember, the parent tells the children what to do! (with occasional cases of flex children properties like flex-grow)
  2. Making everything a flex container - use flex only when you want control over distribution/alignment

The Most Common Flex Properties

  1. Define a parent with display: flex;
  2. Is it a row or column? flex-direction (default row)
  3. How do you want its children to be distributed across the main axis? justify-content
  4. How do you want the children to be aligned on the cross axis? align-items
  5. Do you want elements to wrap if the parent gets too small? flex-wrap

flex-direction

flex-direction

Tip: Practice with this page and the Chrome Inspector using the next few slides.

justify-content

flex-direction

align-items

flex-direction

flex-wrap

flex-direction

flex-grow

flex-direction

Now then... Shall We Dance?

What is a web page, really?

Content

pile of bones

Words and images

Structure

skelton

HTML

Style

skelton

CSS

Behavior

skelton

JavaScript

What We've Learned So Far

How to write content for a webpage using HTML5

How to add styles to a webpage using CSS and linking a CSS file to an HTML file

How to inspect the HTML and CSS of web pages in the browser

(...also Git, some web accessibility, and some design/development strategies as budding web developers!)

CSE 154 Modules

  1. Webpage structure and appearance with HTML5 and CSS.
  2. Client-side interactivity with JS DOM and events.
  3. Using web services (API's) as a client with JS.
  4. Writing JSON-based web services with a server-side language.
  5. Storing and retrieving information in a database with MySQL and server-side programs.

JavaScript is to Java as...

  • Grapefruit → Grape
  • Carpet → Car
  • Hamster → Ham
  • Catfish → Cat
  • Horse → Horseradish

What is JavaScript?

A lightweight "scripting" programming language

Created in 1995 by Brendan Eich (original prototype created in 10 days and called LiveScript)

NOT related to Java other than name and some syntactic similarities...

Used to define interactivity for web pages.

Webpage Behavior with JavaScript

Now that we know how to add content and styles to a web page, lets explore how to add responsive behavior

Over Module 2, we'll use these building blocks to dynamically update what you see on a web page in response to clicks, text input, timers, etc.

Terminology: Client-Side Scripting

client-side scripting

Client-side script: Code that runs on the user's computer and does not need a server to run (just a browser!).

Client-side JavaScript is usually run after HTML and CSS have been loaded on the browser (e.g. from a server response).

Often, this JavaScript manipulates the page or responds to user actions through "event handlers".

JS: Adding Behavior to HTML/CSS

We can use write JavaScript functions to...

  • Insert dynamic text into HTML (ex: username)
  • React to events (ex: page load, user's mouse click)
  • Get information about a user's computer (ex: what browser they are using)
  • ...

Creative Applications of JS in CSE154

Today: Following Along

As an interpreted programming language, JS is great to interact with a line at a time (similar to Python, but very different than Java). Where do you start?

The easiest way to dive in is with the Chrome browser's Console tab in the same inspector tool you've used to inspect your HTML/CSS.

Chrome Console

Until we learn how to interact with the HTML DOM with JS, we recommend experimenting with the following code examples using this console to get comfortable with the basic syntax and behavior.

Our First JavaScript Statement: console.log

Used to output values to the browser console, most often used to debug JS programs. You can think of this as System.out.println in Java or print in Python.

console.log("message");

JS (template)

console.log("The answer is: " + 42);

JS (example)

console.log example

The alert Function

alert("message");

JS (template)

alert("Your browser says hi!");

JS (example)

Demo of browser alert

A JS function that pops up a dialog box with a message - not ideal in practice, but sometimes a recommended debugging tool when first learning JS. Don't include alert statements in any of your assignments.

Comments (similar to Java)

// single-line comment

/**
* multi-line
* comment
*/

JS

Identical to Java's comment syntax

Recall: 3 comment syntaxes

  • HTML: <!-- comment -->
  • CSS/Java/JS: /* comment */
  • Java/JS: // comment

For functions and program files, we'll use JSDoc commenting with @param and @returns, which is covered in the Code Quality Guide here.

Variables

let name = expression;

JS (template)

let level = 23;
let accuracyRate = 0.99;
let name = "Pikachu";

JS (example)

Variables are declared with the let keyword (case-sensitive). You may also see var used instead of let - this is an older convention with weaker scope - DO NOT USE var anywhere

CQG: Use camelCasing for variable (and function) names

"Types" in JavaScript

let level = 23; // Number
let accuracyRate = 0.99; // Number
let name = "Pikachu"; // String
let temps = [55, 60, 57.5]; // Array

JS (example)

Types are not specified, but JS does have types ("loosely-typed")

  • Number, Boolean, String, Array, Object, Function, Null, Undefined
  • Can find out a variable's type by calling typeof, but usually this is poor practice (why?)
  • Note: Type conversion isn't always what you expect...

A Note about Declaring Types in JavaScript

If you've programmed in a statically-typed language like Java, you will recall that when declaring variables, you must specify their type which must always stay the same.

boolean isValid = "hello!"; // error

Java

In a dynamically-typed language like JavaScript, you don't need to specify the type (just use let or const) and you may change the type the variable refers to later in execution.

let isValid = true; // no error
isValid = "hello!";
isValid = 1;

JS

This may seem to imply fewer errors in JS, but it's not uncommon to run into subtle (silent) bugs in your JS programs as a result!

Number Type

let enrollment = 99;
let medianGrade = 2.8;
let credits = 5 + 4 + (2 * 3);

JS

Integers and real numbers are the same type (no int vs. double). All numbers in JS are floating point numbers.

Same operators: + - * / % ++ -- = += -= *= /= %= and similar precedence to Java.

Many operators auto-convert types: "2" * 3 is 6

NaN ("Not a Number") is a return value from operations that have an undefined numerical result (e.g. dividing a String by a String).

Practice!

String type

let nickName = "Sparky O'Sparkz";                  // "Sparky O'Sparks"
let fName = nickName.substring(0, s.indexOf(" ")); // "Sparky"
let len = nickName.length;                         // 15
let name = 'Pikachu';                              // can use "" or ''

JS

Methods: charAt, charCodeAt, fromCharCode, indexOf, lastIndexOf, replace, split, substring, toLowerCase, toUpperCase

More about Strings

Escape sequences behave as in Java: \' \" \& \n \t \\

To convert between Numbers and Strings:

let count = 10;                              // 10
let stringedCount = "" + count;              // "10"
let puppyCount = count + " puppies, yay!";   // "10 puppies, yay!"
let magicNum = parseInt("42 is the answer"); // 42
let mystery = parseFloat("Am I a number?");  // NaN          

JS

To access characters of a String s, use s[index] or s.charAt(index):

let firstLetter  = puppyCount[0];                            // "1"
let fourthLetter = puppyCount.charAt(3);                     // "p"
let lastLetter   = puppyCount.charAt(puppyCount.length - 1); // "!"

JS

Common Bugs when Using Strings

While Strings in JS are fairly similar to those you'd use in Java, there are a few special cases that you should be aware of.

  • Remember that length is a property (not a method, as it is in Java)
  • Concatenation with +: 1 + 1 is 2, but "1" + 1 and 1 + "1" are both "11"!

Practice: repeat

Special Values: null and undefined

          let foo = null;
let bar = 9;
let baz;

/* At this point in the code,
* foo is null
* bar is 9
* baz is undefined
*/

JS

undefined: declared but has not yet been assigned a value

null: exists, but was specifically assigned an empty value or null. Expresses intentional a lack of identification.

A good motivating overview of null vs. undefined

Note: This takes some time to get used to, and remember this slide if you get confused later.

Arrays

let name = [];                          // empty array
let names = [value, value, ..., value]; // pre-filled
names[index] = value;                   // store element

JS (template)

          let types = ["Electric", "Water", "Fire"];
let pokemon = [];        // []
pokemon[0] = "Pikachu";  // ["Pikachu"]
pokemon[1] = "Squirtle"; // ["Pikachu", "Sqiurtle"]
pokemon[3] = "Magikarp"; // ["Pikachu", "Sqiurtle", undefined, "Magikarp"]
pokemon[3] = "Gyarados"; // ["Pikachu", "Sqiurtle", undefined, "Gyarados"]

JS (example)

Two ways to initialize an array

length property (grows as needed when elements are added)

Some Notes on Typing

As you write JS programs, you may will run into some silent bugs resulting from odd typing behavior in JS. Automatic type conversion, or coercion, is a common, often perplexing, source of JS bugs (even for experienced JS programmers).

Why is this important to be aware of? You'll be writing programs which use variables and conditional logic. Knowing what is considered truthy/false and how types are evaluated (at a high level) can make you a much happier JS developer (some practice)

Examples of some "not-so-obvious" evaluations:

2 < 1 < 2;// true

0 + "1" + 2;// "012"

[] + [];// ""

"1" / null;// Infinity

[+!![]]+[[![]+!![]]];// "11"

This is worth 3 minutes of your viewing pleasure. (starting at 1:20)

Defining Functions

function name(params) {
  statement;
  statement;
  ...
  statement;
}

JS (template)

          function myFunction() {
  console.log("Hello!");
  alert("Your browser says hi!");
}

JS (example)

The above could be the contents of basics.js linked to our HTML page

Statements placed into functions can be evaluated in response to user events

Practice: fixErrors2 , containsTwice , functionMystery1 , sumUpTo , veryBestSong

JS Function vs. Java Method

function repeat(str, n) {
  let result = str;
  for (let i = 1; i < n; i++) {
    result += str;
  }
  return result;
  }
  let repeatedStr = repeat("echo...", 3); // "echo...echo...echo..."
}

JS (example)

public static String repeat(String str, int n) {
  String result = str;
  for (int i = 1; i < n; i++) {
    result += str;
  }
  return result;
  }
  String repeatedStr = repeat("echo...", 3); // "echo...echo...echo..."
}

Java (example)

JS Function vs. Python Function

function repeat(str, n) {
  let result = str;
  for (let i = 1; i < n; i++) {
    result += str;
  }
  return result;
  }
  let repeatedStr = repeat("echo...", 3); // "echo...echo...echo..."
}

JS (example)

def repeat(str, n):
  result = str;
  for i in range(1, n):
    result = result + str;
  return result;
  
  repeatedStr = repeat("echo...", 3) // "echo...echo...echo..."

Python (example)

From the Console to a .js File

Now, we'll use these building blocks of a new programming language to control the behavior of our pages (which we don't get with HTML/CSS!).

Activity

Mystery Box DOM UI breakdown

JS/HTML Connection

In general, to add interactivity to our HTML/CSS websites we need to:

  1. Link a JS program to our HTML (in the <head>)
  2. Identify the elements we want to "listen" to user/page events
  3. Identify the events we want to respond to
  4. Identify what each response function is
  5. Assign the listener elements the functions when the event(s) occurs! own event(s) to listen to

Our Toolbox So Far: HTML/CSS + JS

HTML, CSS, and JS on the browser Image source (MDN) and recommended reading

So far, we have used VSCode (or a similar editor) to write HTML/CSS for the structure/styles for our page. We will continue to use VSCode to write JavaScript and add behavior.

As always, the webpage is rendered by the browser. We will add a link to our JS from HTML (similar to the idea of linking a CSS file) and the browser will execute the JS after the HTML/CSS has been loaded.

Linking to a JavaScript file: <script>

<script src="filename"></script>

HTML (template)

<script src="example.js"></script>

HTML (example)

The script tag should be placed in the HTML page's head.

All JavaScript code used in the page should be stored in a separate .js file

JS code can be placed directly in the HTML file's body or head (like CSS), but this is poor code quality. You should always separate content, presentation, and behavior

Here's a basics.html linked to this basics.js - feel free to use these to practice with!

Accessing Elements from the document object in JavaScript

Accessing an Element by ID

let name = document.getElementById("id");

JS

  • document.getElementById returns the DOM object for an element with a given id (note that you omit the # when giving an id)
  • We'll learn about other ways to get DOM elements (e.g. document.querySelector to get elements by class name) Wednesday!

What's inside a DOM object?

For starters, the HTML attributes. This HTML:

<img src="images/puppy.png" alt="A fantastic puppy photo"/>

HTML

Has a DOM object (let's call it puppyImg) with these two properties:

  • puppyImg.src -- set by the browser to images/puppy.png
  • puppyImg.alt -- set by the browser to "A fantastic puppy photo"

Listening to Events with JS/HTML

There are a ton of HTML tags that are used to build UI (user interfaces).

Enter Text: <input type="text" id="input-text" /> <Go!>

HTML

Enter Text:

output

We'll start with the humble button today, but we'll learn a few more like input boxes and dropdowns next week.

The <button>

<button id="my-btn">Click me!</button>

HTML

output

Text inside of the button tag renders as the button text

To make a responsive button (or other UI controls):

  1. Choose the control (e.g., button) and event (e.g., mouse click) of interest
  2. Write a JavaScript function to run when the event occurs
  3. Attach the function to the event on the control

Event-Driven Programming

event-driven programming

Unlike Java programs, JS programs have no main; they respond to user actions called events

Event-Driven Programming: writing programs driven by user events

Listening and Responding to Events with addEventListener

function handleFunction() {
  // event handler code
}
// attaching a named function
element.addEventListener("click", handleFunction);

JS (onclick template)

  • JavaScript functions can be set as event handlers (also known as "callbacks")
  • When you interact with the element and trigger the event, the callback function will execute

Using a click Event Handler to Open the Mystery Box

<img id="mystery-box" src="question-block.png" alt="A Mystery Box" />
<button id="box-btn">Click me!</button>

HTML

let boxBtn = document.getElementById("box-btn");
boxBtn.addEventListener("click", openBox);

function openBox() {
  let box = document.getElementById("mystery-box"); // 1. Get the box image
  box.src = "star.png"; // 2. Change the box image's src attribute!
}

JS

a mystery box

output

JavaScript "strict" mode

"use strict";

...your code...

JS

Writing "use strict"; at the very top of your JS file turns on strict syntax checking:

  • Shows an error if you try to assign to an undeclared variable
  • Stops you from overwriting key JS system libraries
  • Forbids some unsafe or error-prone language features

You should always turn on strict mode for your code in this class!

More questions from this lecture?

Especially if you're watching a recording, write your question on PollEverywhere and I'll answer them at the start of next lecture.

Either on your phone or computer, go to PollEv.com/robcse