Lecture 6

Introduction to JavaScript

Course Logistics

HW 2 is out (layouts and flexboxes): Due Wednesday (October 11th)

Part 2 of the Creative Project is due tonight. I have office hours in CSE 216 right after lecture! Great work so far :)

What We've Learned So Far

How to write content for a webpage using HTML

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

Today: JavaScript

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

This lecture we'll cover the basics of the JavaScript language:

  • JavaScript vs. Java comparisons
  • Syntax and types
  • Loops and functions
  • Events (basics) and form elements

Later this week we'll use these building blocks to learn how 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 runs in browser after page is sent back from server. Often, this code manipulates the page or responds to user actions.

What is JavaScript?

A lightweight programming language ("scripting language")

Created in 1995 (over 10 days) by Brendan Elch (originally called Mocha then LiveScript)

Used to make web pages interactive:

  • 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)
  • Perform calculations on user's computer (ex: form validation)

A web standard (but not supported identically by all browsers)

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

Can be used in the browser, Adobe Acrobat, Adobe Photoshop, embedded computers, the Unix terminal, etc. (we will be using it in the browser)

JavaScript vs. Java

Interpreted, not compiled (huh?)

More relaxed syntax and rules

  • Fewer and "looser" data types
  • Variables don't need to be declared
  • Errors often silent (few exceptions)

JavaScript's key construct is the function rather than the object/class.

  • "first-class" functions are used in many situations

Contained within a web page and integrates with its HTML/CSS content

Linking to a JavaScript file: <script>

            
              
          

HTML (template)

            
              
          

HTML (example)

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

Script code is stored in a separate .js file

JS code can be placed directly in the HTML file's body or head (like CSS)

  • This is bad style though: You should always separate content, presentation, and behavior

Our First JavaScript Statement: alert

            
              alert("message");
          

JS (template)

            
              alert("IE6 detected. Suck-mode enabled.");
          

JS (example)

never use internet explorer

A JS command that pops up a dialog box with a message

Variables and types

            
            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, and you should use let in this class.

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

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)

Same operators: + - * / % ++ -- = += -= *= /= %=

Similar precedence to Java

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

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

  • charAt returns a one-letter String (there is no char type)

length is a property (not a method, as it is in Java)

Concatenation with +: 1 + 1 is 2, but "1" + 1 is "11"

Practice: repeat, containsTwice

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

Comments (same as 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

Practice: commentSyntax, commentary

for loop (same as Java)

            
            for (initialization; condition; update) {
              statements;
            }
          

JS (template)

            
              let sum = 0;
              for (let i = 0; i < 100; i++) {
                sum = sum + i; // same as sum += i;
              }
          

JS (example)

            
              let s1 = "It's a-me, Mario!";
              let s2 = "";
              for (let i = 0; i < s.length; i++) {
                s2 += s1[i] + s1[i];
              }
              // s2 stores "IItt''ss  aa--mmee,,  MMaarriioo!!" 
          

JS (example)

Math object

            
              let rand1to10 = Math.floor(Math.random() * 10 + 1);
              let three = Math.floor(Math.PI);
          

JS

Methods: abs, ceil, cos, floor, log, max, min, pow, random, round, sin, sqrt, tan

Properties: E, PI

Logical Operators

Relational: > < >= <=

Logical: && || !

Equality: == != === !==

  • Most logical operators automatically convert types. These are all true:
    • 5 < "7"
    • 42 == 42.0
    • "5.0" == 5
  • The === and !== are strict equality tests; checks both type and value: "5.0" === 5 is false

Boolean Type

            
              let iLikeJS = true;
              let ieIsGood = "IE6" > 0; // false
              if ("web dev is great") { /* true */ }
              if (0) { /* false */ }
          

JS

Any value can be used as a Boolean

  • "falsey" values: 0, 0.0, NaN, "", null, and undefined
  • "truthy" values: anything else

Converting a value into a Boolean explicitly:

  • let boolValue = Boolean(otherValue);
  • let boolValue = !!(otherValue);

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: has not been declared, does not exist

null: exists, but was specifically assigned an empty or null value

Why does JavaScript have both of these?

if/else Statements (same as Java)

            
              if (condition) {
                statements;
              } else if (condition) {
                statements;
              } else {
                statements;
              }
          

JS

Identical structure to Java's if/else statements

JavaScript allows almost anything as a condition

Practice: rockPaperScissors

while loops (same as Java)

            
            while (condition) {
              statements;
            }
          

JS

            
            do {
              statements;
            } while (condition);
            

JS

break and continue keywords also behave as in Java but do not use them in this class!

Practice: loopMystery6

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)

Array methods

            
            let a = ["Mario", "Luigi"]; // [Mario, Luigi]
            a.push("Koopatroopa");      // [Mario, Luigi, Koopatroopa]
            a.unshift("Bowser");        // [Bowser, Mario, Luigi, Koopatroopa]
            a.pop();                    // [Bowser, Mario, Luigi]
            a.shift();                  // [Mario, Luigi]
            a.sort();                   // [Luigi, Mario]
          

JS

Array serves as many data structures: list, queue, stack, ...

Methods: concat, join, pop, push, reverse, shift, slice, sort, splice, toString, unshift

  • push and pop add/remove from back
  • shift and unshift add/remove from front
  • shift and pop return the element that is removed

Practice: findMin , switchPairs

Splitting strings: split and join

            
              let s = "the quick brown fox";
              let a = s.split(" "); // ["the", "quick", "brown", "fox"]
              a.reverse();          // ["fox", "brown", "quick", "the"]
              s = a.join("!");      // "fox!brown!quick!the"
          

JS

split breaks apart a String into an array using a delimiter

  • Can also be used with regular expressions surrounded by /:
    let a = s.split(/[ \t]+/);

join merges an array into a single String, placing a delimiter between them

Defining functions

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

JS (template)

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

JS (example)

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

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

Practice: functionMystery1, sumUpTo, veryBestSong

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

Event Handlers

            
              <element attributes onclick="function();">...
          

HTML (template)

            
              <div onclick="myFunction();">Click me!</div>
          

HTML (example)

Click me!

output

JavaScript functions can be set as event handlers

When you interact with the element, the function will execute

onclick is just one of many event HTML attributes we'll use

Buttons: <button>

            
              <button onclick="myFunction();">Click me!</button>
          

HTML

output

Button's text appears inside tag; can also contain images

To make a responsive button or other UI control:

  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

Accessing an Element: document.getElementById

            
            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)

document.getElementById: An Example

            
            <img id="pokeball" src="images/pokeball.jpg" alt="a pokeball" />
            <button onclick="changeImage();">Click me!</button>
          

HTML

            
            function changeImage() {
              let pokeballImg = document.getElementById("pokeball");
              pokeballImg.src = "images/mystery.gif";
            }
          

JS

a pokeball

output

So... how can JavaScript be useful on a webpage?

A common use for JavaScript on webpages is for event-handling and form validation.

To use form validation, we need to learn about a few more HTML tags...

Form Elements: <input>

            
            <!-- 'q' happens to be the name of Google's required paramter -->
            <input type="text" name="q" value="Colbert Report" />
            <input type="submit" value="Booyah!" />
          

HTML

output

Input element is used to create many UI controls (an inline element that must be self-closed

name attribute specifies name of query parameter to pass to server

type can be button, checkbox, file, hidden, password, radio, reset, submit, text, ...

value attribute specifies control's initial text

<input> text fields

            
              <input type="text" size="10" maxlength="8" /> NetID <br />
              <input type="password" size="16" /> Password
              <input type="submit" value="Log In!" />
            

HTML

NetID
Password

output

input attributes: disabled, maxLength, readonly, size, value

size attribute controls onscreen width of text field

maxlength limits how many characters the user is able to type into the field

Form Elements: Text boxes: <textarea>

            
              <textarea rows="4" cols="20">
              Type your comments here.
              </textarea>
          

HTML

output

Initial text is placed inside textarea tag (optional)

Required rows and cols attributes specify height/width in characters

optional readonly attribute means text cannot be modified

Resources and Tips

Review programming basics: using variables, arrays, loops, if-statements, and functions

Go over some JavaScript tutorials - there are many great ones!

Practice! We now have JavaScript problems on Practice-It (80+ problems) and its sister site CodeStepByStep (200+ problems).

Check out cool examples of JavaScript on the web!