On your lecture handouts, discuss and respond to the following question (and optionally include a sketch):
Note: We will collect these at the end of the class (optional) - we might add some creative ideas to additional section exercises!
Administrivia
Introduction to Module 2
JavaScript Basics
Milestone due Tuesday (remember, no late days!)
For full credit, the Main Menu View (Part A) must be stylistically complete. This includes some requirements listed in Overall Appearance and example screenshot.
The Game View should be hidden - make sure to implement the .hidden
class to achieve this for Part A.
CP1 Showcase is up and CP2 out today! Checkout previous showcases (linked from CP2 spec) for some inspiration of how students explored JS in different ways.
Important: Moving forward (CP2 and later) we are enforcing a requirement that all files follow lower-cased naming conventions. Please refer to CP2 spec and Code Quality Guide for more information.
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
Git!
Now that we know how to add content and styles to a web page, lets explore how to add responsive behavior
These slides will introduce the basics of the JavaScript language:
Soon, we'll use these building blocks to dynamically update what you see on a web page in response to clicks, text input, timers, etc.
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".
A lightweight "scripting" programming language
Created in 1995 by Brendan Eich (original prototype created in 10 days and called LiveScript)
Used to make web pages interactive:
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, as well as Adobe Photoshop, embedded computers, the Unix terminal, etc. (we will be using it in the browser)
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.
Until we learn functions to interact with the HTML DOM with JS, we recommend experimenting with the following code examples using this console to get comfortable with the fundamental syntax and behavior of the language.
console.log
Used to output values to the browser console, most often used to debug JS programs.
console.log("message");
JS (template)
console.log("The answer is: " + 42);
JS (example)
alert
Functionalert("message");
JS (template)
alert("IE6 detected. Suck-mode enabled.");
JS (example)
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.
// 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.
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
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
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!
Since ECMA6, JavaScript has a special keyword to declare "constant" values. You should
use these over the let
keyword for variables that are not intended to ever
be updated (similar to constants in Java).
CGQ: Use UPPER_CASING
naming conventions to
denote const
in JS.
let month = 12;
month = 1; // no error
const COOLEST_CLASS = "CSE154";
COOLEST_CLASS = "clazz"; // error
JS
These can help avoid some of the bugs
mentioned on the previous slide (an error occurs when trying to reassign a
const
).
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: + - * / % ++ -- = += -= *= /= %=
Similar precedence to Java
Many operators auto-convert types: "2" * 3
is 6
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
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
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.
length
is a property (not a method, as it is in Java)+
: 1 + 1
is 2
, but "1" +
1
and 1 + "1"
are both "11"
!
Practice: repeat
, containsTwice
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
function mystery(a, b) {
if (a > b) {
return 0;
} else {
let result = 0;
for (let i = a; i <= b; i++) {
result += i;
}
return result;
}
}
JS (template)
Q: What does this code do? What does mystery(4, 6)
return? How would you
use the function to get a result of 10?
*Image created by Lauren using imgflip
for
Loops (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)
See below slides for comparisons in Java/Python
for
Loop Comparisonslet 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)
String s1 = "It's a-me, Mario!";
String s2 = "";
for (int i = 0; i < s.length(); i++) {
s2 += s1.charAt(i) + s1.charAt(i);
}
Java (example)
s1 = "It's a-me, Mario!";
s2 = "";
for i in range(len(s1)):
s2 += s1[i] + s1[i];
Python (example)
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 (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
Relational: > < >= <=
, Logical: && || !
,
Equality: === !== == !=
5 < "7"
42 == 42.0
"5.0" == 5
===
and !==
are strict equality tests; checks both
type and value: "5.0" === 5
is false
. It's
almost always best to use ===
instead of ==
.
154 === 154.0
evaluate to?Helpful JavaScript equality table!
let iLikeJS = true;
let ieIsGood = "IE6" > 0; // false
if ("web dev is great") { /* true */ }
if (0) { /* false */ }
if (1) { /* true */ }
JS
Any value can be used as a Boolean
false
, 0
, NaN
,
""
, null
, and undefined
Understanding what is "falsey" vs. "truthy" takes patience and practice.
When in doubt, check in the browser console!
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)
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 backshift
and unshift
add/remove from frontshift
and pop
return the element that is removed
Practice:
findMin
,
switchPairs
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
let a = s.split(/[ \t]+/);
join
merges an array into a single String, placing a delimiter between
them
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
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)
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)
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!).
We introduced different form element tags offered in HTML
But they're not too helpful if we can't do anything with them!
In general, to add interactivity to our HTML/CSS websites we need to:
<head>
)
Unlike Java programs, JS programs have no main
; they respond to user actions
called events
Event-Driven Programming: writing programs driven by user events
<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!
Name | Description |
---|---|
click | A pointing device button (e.g. mouse) has been pressed and released on an element |
dblclick | A pointing device button is clicked twice on an element |
keydown | Any key is pressed down |
keyup | Any key is released |
mouseenter | A pointing device is moved onto an element that has the attached |
mouseover | A pointing device is moved onto the element that has the listener attached to itself or one of its children |
mousemove | A pointing device is moved over an element |
mousedown | A pointing device button is pressed on an element |
mouseup | A pointing device button is released over an element |
We'll cover more later (you can find a full list here),
but today we'll demo click
!
addEventListener
function handleFunction() {
// event handler code
}
// attaching a named function
element.addEventListener("click", handleFunction);
JS (onclick template)
element.onclick
(see example
and more information on slide below)
onevent
handlers
Example with onclick
(same effect as previous slide):
// attaching a named function
function handleFunction() {
// event handler code
}
element.onclick = handleFunction;
JS (onclick template)
The newer addEventListener
is preferred as it lets you easily
remove a listener to a specific event on an element, and it also lets you add
multiple functions to an event listener. For this example, that doesn't make a
difference, but we will see examples where it does!
More information about tradeoffs here.
Finally... the fun starts.
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)
<button>
<button id="my-btn">Click me!</button>
HTML
output
Button's text appears inside tag; can also contain images
To make a responsive button or other UI control:
Right now this button doesn't do anything when we click it. That's because it doesn't have event handler code attached :( Let's see an example where we do have an event listener attached to a button on our page!
click
Event Handler: an Example<img id="pokeball" src="images/pokeball.jpg" alt="a pokeball" />
<button id="demo-btn">Click me!</button>
HTML
let demoButton = document.getElementById("demo-btn");
demoButton.addEventListener("click", changeImage);
function changeImage() {
let pokeballImg = document.getElementById("pokeball");
pokeballImg.src = "images/mystery.gif";
}
JS
output
We'll learn more about this tomorrow, but in order for our JS to work when
attached to an HTML file, we need to wrap any code that interacts with the
document inside the window's load
event
handler. load
is the event listened to on the window to indicate when
the page "is loaded".
When the page is loaded, everything in the
attached function (in our example, we call this main
),
is executed, including any click
attachments!
// listener attached before page is loaded
window.addEventListener("load", init);
function init() {
// this code is ran after page is loaded!
let demoButton = document.getElementById("demo-btn");
demoButton.addEventListener("click", changeImage);
}
function changeImage() {
let pokeballImg = document.getElementById("pokeball");
pokeballImg.src = "images/mystery.gif";
}
button-example.js (commented example)
You can see the HTML output here. On Wednesday, we'll add one more important component to our JS files: the module pattern.
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!