Introduction to Programming and JavaScript
What is JavaScript?
- Originally named "LiveScript" by its originator, Netscape (oh how the once almighty has fallen)
- Client-side scripting / programming language
- Embedded within a web page
- Integrates with HTML and CSS content
- (Still) the biggest misconception: it is not related by any means to the Java programming language!
- Rumored that Netscape changed the name to JavaScript to capitalize on monetary associations with coffee
- There is also JScript, Microsoft's version of JavaScript
- C-like syntax
- cAsE sEnSiTiVe
- Comments:
//
- single line/*
- multi lines
*/
Client-Side Tasks (or What You Can Do With JavaScript)
- Dynamically modify browser content, e.g., with animation
- Dynamically fetch new documents from servers
- Allow new methods of user interaction other than links and buttons
- Get information about a user's computer
Variables
- Variable type is determined by what you set a variable to
i = 'hello';
- a stringi = 2.45;
- a floating point numberi = 4;
- an integer
Special Values
null
- return value when the result is nothingundefined
- value of something that hasn't been set yet- There is a real boolean type with the special values
true
andfalse
NaN
Infinity
- Thus a variable can have three states
- Not set yet (undefined)
- Set to nothing (null)
- Set to a valid value
Operators
- The usual arithmetic gang: +, -, * , /, %
- The usual conditional gang: &&, ||, !, ==
==
just checks value===
also checks type (i.e., exactly equal to). Example:10 === "10"
is false- Many operators auto-convert types. Example:
5 < "7"
is true - a < b, a > b, etc., work on both numbers and strings. For strings, you get alpha order. For numbers, you get numeric order.
- String concatenation:
+
Adding JavaScript to HTML
- Three ways:
- In the page's <body> (runs when page loads) --ugh!
- In the page's <head> (runs when events occur)
- In a link to an external
.js
script file- Example:
<script type="text/javascript" src="ajax.js" />
- Example:
- Example: JavaScript in HTML body (always runs on page load; useful for generating dynamic text)
<body> <script type="text/javascript"> ... ... ... </script> </body>
- Example: JavaScript in HTML header (does not run unless functions are explicitly called; useful for event-triggered actions)
<head> <script type="text/javascript"> ... ... ... </script> </head>
- Another Useless Example: Factorials
<!DOCTYPE html> <html> <head> <title>COMP 20: Web Programming</title> </head> <body> <script type="text/javascript"> document.write("<h1>Factorials</h1>"); var fact = 1; for (i = 1; i <= 100; i++) { fact *= i; document.write(i + '! = ' + fact); document.write('<br/>'); } a = 25; console.log(a * 2); console.log("Microfridge"); </script> </body> </html>
Functions
- Parameter and return types are not written (not even
var
on parameter declarations) - Can return any return type
- Functions with no return statement return an
undefined
value - Variables declared in the function are local
- Wrong number of parameters used?
- Too many: extras ignored
- Too few: remainders get an
undefined
value
- Example:
<script type="text/javascript"> function silly (x,y) { i = 5; var j = x*y; return i * j; } var y = silly(2, 3); document.write("The result of silly(2,3) is " + y + "<br/>"); </script>
Packages and Namespace
- JavaScript has the concept of packages
- A package allows similar functions to be accessed through a common "library name"
- One accesses packages via dot notation; applies to both functions and data
- Special package
Number
holds a bunch of numeric constants Number.MAX_VALUE
Number.MIN_VALUE
Number.NaN
(e.g., result of dividing by 0)Number.POSITIVE_INFINITY
Number.NEGATIVE_INFINITY
- Special package
- Example:
var i = Math.sqrt(2);
sets i to the square root of 2 - To call a function in JavaScript, you must remember which package it's in
String Object
- Example:
var name = 'Peter Griffin';
- Methods:
charAt
--returns a string!indexOf
lastIndexOf
replace
split
substring
toLowerCase
toUpperCase
- Example:
var firstName = s.substring(0, s.indexOf(" "));
- Properties
length
- Complete list of methods
- Stringification: when you have a thing, and need a string, call the special (reserved) method
thing.toString()
to get one
Math
Object
- Methods:
abs
ceil
cos
floor
log
max
min
pow
random
--returns a random number between 0 and 1round
sin
sqrt
tan
- Properties
E
PI
- Examples:
var lottery1 = Math.floor(Math.random() * 9);
,var two = Math.floor(Math.E);
- Complete list of methods and properties
Date
Object
- Example:
var due = new Date(2009, 10, 5);
- Complete list of methods and properties
- Watch out!
getYear
returns a 2-digit year; usegetFullYear
insteadgetDay
returns day of week from 0 (Sun) through 6 (Sat)getDate
returns day of month from 1 to # of days in monthDate
stores month from 0 - 11 (not from 1 - 12)
- What is nice: you can compare two dates. Example:
var targetDate = new Date(); targetDate.setFullYear(2011, 2, 14); var today = new Date(); if (targetDate > today) { document.write("Output: Today is before PI Day, 3/14/2011"); } else if (targetDate == today) { document.write("Output: Today is PI Day!"); } else { document.write("Output: Today is after PI Day, 3/14/2011"); }
Popup Boxes
alert('XSS');
- Message boxconfirm('Are you sure you want to delete all records?');
- Confirmation; returns true or falseprompt('What is your name?');
- Returns user input string
Arrays
- Three ways to initialize an array:
var names = Array(); names[0] = 'Tom';
var names = Array('Tom', 'Dick', 'Harry');
var names = ['Tom', 'Dick', 'Harry'];
- Arrays don't have fixed dimensions
- They automatically resize as you add data
- No such thing as a fixed length array
- Example:
<script type="text/javascript"> var a = new Array(); a[0] = 1; a[1] = "hi there"; a[2] = 5.6; a[3] = "data"; a[7] = "values"; a[12] = "can"; a[15] = "be"; a[19] = "anything"; for (i = 0; i < a.length; i++) { document.write("a[" + i + "]=" + a[i] + "<br/>\n"); } </script>
- Try the above:
js_array1.html
- Complete list of array methods and properties
concat
join
push
--adds element to end of array and returns new list sizeshift
--removes and returns element at beginning of listpop
--removes and returns element at end of arrayunshift
--adds element to front of array and returns new list sizesort
- Examples:
names.push('Michael');
names.push('Janet', 'Jermaine');
names.unshift('LaToya');
names.sort();
names.pop();
Global DOM Objects
window
- The browser window- Example 1:
window.close()
- Closes the current window - Example 2:
window.pageYOffset
- Sets or returns the Y position of the current page in relation to the upper left corner of a window's display area
- Example 1:
navigator
- Information about the web browser you are using- Example:
navigator.userAgent
- Returns the value of the user-agent header sent by the client to the server
- Example:
screen
- Information about the screen occupied by the web browser- Example:
screen.width
- Returns width of the display screen
- Example:
history
- List of pages the user has visiteds- Example:
history.go(-1)
- Go back to the previous page (if any)
- Example:
location
- URL of the current document- Example:
location.pathname
- Sets or returns the path of the current URL
- Example:
document
- Current HTML page object model- Example 1:
document.getElementsByTagName("some tag")
- Get all elements of a certain type; returns an array - Example 2:
var element = document.getElementById("some ID")
- Get a specific element on the page; returns an element- Example 2A:
element.getElementsByTagName("some tag")
- Same as above; returns an array
- Example 2A:
- Example 3:
document.createElement("some element")
- Example 1: