CS 80: Internet Programming
Instructor: Mark Edmonds
Why do we care?
<script>
HTML element allows us
to add Javascript to our HTML document
<head>
portion of the documentExample:
<script type="text/javascript"> script_stuff </script>
hello_world.html
<!DOCTYPE html>
<!-- Fig. 6.1: welcome.html -->
<!-- Displaying a line of text. -->
<html>
<head>
<meta charset="utf-8">
<title>A First Program in JavaScript</title>
<script type="text/javascript">
// the document object accesses the current HTML document
// writeln is a method that writes a line to the document
// the enclosed argument to writeln is the content to write to the document
document.writeln("<h1>Welcome to JavaScript Programming!</h1>");
</script>
</head>
<body>
<!-- Notice our empty body -->
</body>
</html>
hello_world.html
document
is the HTML document, represented
through a javascript object
.writeln()
is a method within the
document
object
ln
)"<h1>Welcome to JavaScript
Programming!</h1>"
is a
string and is the content to write
to the HTML documentExample
<script src="srcipt.js">
Loads the Javascript in srcipt.js
into
this HTML document
Statements and Keywords
var
is an example
;
, as in hello_world.html
Variables
var myVar;
var myVar, myVar1,
myVar2;
myVar = 5;
hello_world_variables.html
<!DOCTYPE html>
<!-- Fig. 6.1: welcome.html -->
<!-- Displaying a line of text. -->
<html>
<head>
<meta charset="utf-8">
<title>A First Program in JavaScript</title>
<script type="text/javascript">
// declare a variable to hold our string
var text = "<h1>Welcome to JavaScript Programming!</h1>";
var myDocVar = document;
// use the variables to write the content to the document
myDocVar.writeln(text);
</script>
</head>
<body>
<!-- Notice our empty body -->
</body>
</html>
Variables
var
be assigned to a string
(hello_world_variables.html
) and to a
number (above, myVar =5;
).
var
represents any variable,
could be a string, could be an intmyVar = 5; myVar =
"cheese";
)Variables
var myVar = "cheese";
var
myVar = 5;
var myVar = true;
Variables
var myVar = [5, "cheese",
false];
myVar[0]
is 5
,
myVar[2]
is false
var myVar = document;
myVar
)//
/*
ends with
*/
var myVar = 5;
var myVar = "cheese";
Basic Operators
Basic Operators
+
, used to add two numbers together, or
merge two strings
6 + 9;
yields 15
"Hello " + "world!"
yields
"Hello world!"
Basic Operators
-
, *
, /
, used
just as they in basic math (you can't divide a string
by another string, concatenation is special!)
6 * 5;
yields 30
Basic Operators
=
, we've
already seen this. It's used to take a value (either an
object or a literal) and assign it another object
(typically a variable)
var myVar = 6 * 5;
assigns
myVar
to 30
Basic Operators
%
, used to
perform modulo.
11 % 5
yields 1
because 11 = 5 * 2 + 1
1
,
since that is the remainder when you divide
11
by 5
Opertaor Precedence
Escape Sequences
\n
: a new line (carriage return, like
hitting enter)\t
: a tab\\
: a literal backslash (since
\
normally has special meaning - to escape
other characters!)\"
: double quote - for nested double
quotes
\'
: single quote - for nested single
quotes
Examples
alert.html
window
object refers the browser's
windowalert
opens a dialog to display the
stringwindow
methods and
attributes: http://www.w3schools.com/jsref/obj_window.asp
alert.html
<!DOCTYPE html>
<!-- Fig. 6.3: welcome3.html -->
<!-- Alert dialog displaying multiple lines. -->
<html>
<head>
<meta charset="utf-8">
<title>Printing Multiple Lines in a Dialog Box</title>
<script type="text/javascript">
// Your book does the following <!-- // --> pattern inside the script tag all the time
// DONT DO THIS! It's for ANCIENT browsers that do not support scripts (and interprets them as an HTML comment)
// Seriously, I cannot stress how pointless this practice is, and you should not be doing it
<!--
window.alert("Welcome to\nJavaScript\nProgramming!");
// -->
</script>
</head>
<body>
<p>Click Refresh (or Reload) to run this script again.</p>
</body>
</html>
Examples
dynamic_welcome.html
window
with
prompt()
method to ask for user
inputdynamic_welcome.html
<!DOCTYPE html>
<!-- Fig. 6.5: welcome4.html -->
<!-- Prompt box used on a welcome screen -->
<html>
<head>
<meta charset="utf-8">
<title>Using Prompt and Alert Boxes</title>
<script type="text/javascript">
var name;
// string entered by the user
// read the name from the prompt box as a string
name = window.prompt("Please enter your name");
document.writeln("<h1>Hello " + name + ", welcome to JavaScript programming!</h1>");
</script>
</head>
<body></body>
</html>
Examples
addition.html
parseInt()
function converts a
string to an integeraddition.html
<!DOCTYPE html>
<!-- Fig. 6.7: addition.html -->
<!-- Addition script. -->
<html>
<head>
<meta charset="utf-8">
<title>An Addition Program</title>
<script type="text/javascript">
<!--
var firstNumber; // first string entered by user
var secondNumber; // second string entered by user
var number1; // first number to add
var number2; // second number to add
var sum; // sum of number1 and number2
// read in first number from user as a string
firstNumber = window.prompt("Enter first integer");
// read in second number from user as a string
secondNumber = window.prompt("Enter second integer");
// convert numbers from strings to integers
number1 = parseInt(firstNumber);
number2 = parseInt(secondNumber);
sum = number1 + number2; // add the numbers
// sum = firstNumber + secondNumber; // add the numbers (as strings)
// display the results
document.writeln("<h1>The sum is " + sum + "</h1>");
// -->
</script>
</head>
<body></body>
</html>
Operators and Conditionals
Operators and Conditionals
Example:
// basic conditional
if(5 <= 10){
document.writeln("5 is indeed less than 10");
} else {
document.writeln("5 is somehow not less than 10...");
}
Operators and Conditionals
if(cond)...else
if(cond)...else...
)Operators and Conditionals
Example: where time
is the hour of the
day (0-23)
// order of the conditionals matters; what happens if we flip them?
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
Equality and Relational Operators
Operators and Conditionals
===
and
==
===
is a more strict comparison
operator"75" == 75
yields true but
"75" === 75
yields falseOperators and Conditionals
AND
,
OR
, and NOT
AND
is represented with
&&
OR
is represented with
||
NOT
is represented with
!
Operators and Conditionals
cond_a
is
true
and cond_b
is
false
.
if(cond_a || cond_b)
doens't
need to look at the value of cond_b
,
the overall condition is determined by
cond_a
.if(cond_b &&
cond_a)
doesn't need to look at the value
of cond_a
, since cond_b
already determined the overall state of the
compound conditional.Operators and Conditionals
Example: (pay close attention to evaluation order)
// be careful analyzing this conditional
if(cond_a && cond_b){
// only executes if cond_a AND cond_b are true
} else if(cond_a || cond_d){
// only executes if 1) (cond_a is true AND cond_b is false (think about why)) OR cond_d is true
} else if(!cond_d){
// only executes if cond_a is false AND cond_d is false
} else {
// will this ever execute?
// otherwise
}
Display the current day and time in the following format:
Today is: Friday
Current time is: 4:50:22PM
First step: look at the
Date()
javascript function
date_print.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Display Date</title>
<script type="text/javascript">
var today = new Date();
var day = today.getDay();
var daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ", "Thursday", "Friday", "Saturday"];
document.writeln("Today is: " + daylist[day] + "<br>");
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
console.log("hour: " + hour);
var postpand = "";
if (hour >= 12) {
postpand = "PM";
} else {
postpand = "AM";
}
// special case for midnight
if (hour == 0){
hour == 12;
}
// convert military time to AM/PM hours
if (hour > 12) {
hour = hour - 12;
}
if (minute < 10) {
minute = "0" + minute;
}
if (second < 10) {
second = "0" + second;
}
document.writeln("Current time is: " + hour + ":" + minute + ":" + second + postpand);
</script>
</head>
<body>
</body>
</html>
leap_year_checker.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Leap Year Checker</title>
<script type="text/javascript">
var year, leapYear = false,
leapYearText = "";
year = parseInt(window.prompt("Input a year: "));
if (year % 100 === 0) {
if (year % 400 === 0) {
leapYear = true;
}
} else if (year % 4 === 0) {
leapYear = true;
}
if (!leapYear) {
leapYearText = " not";
}
document.writeln("<h2>" + year + " is" + leapYearText + " a leap year</h2>");
</script>
</head>
<body>
</body>
</html>
Functions enable reuseable code
Sum example:
// function declaration
function sum1(a, b){
// do other amazing javascript things here
return a + b;
}
We can then call sum(10, 5)
which would
return 15
Assigning functions to variables
Sum example:
// anonymous function assigned to variable
var sum2 = function(a,b){
return a + b;
}
We can then call sum2(10, 5)
which
would return 15
Hoisting
sum1
are "hoisted" to the top
of your program, meaning they can be used before
they are declared