Except where otherwise noted, the contents of this document are Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the author's expressed written permission.
var name = []; // empty array var name = [value, value, ..., value]; // pre-filled name[index] = value; // store element
var ducks = ["Huey", "Dewey", "Louie"]; var stooges = []; // stooges.length is 0 stooges[0] = "Larry"; // stooges.length is 1 stooges[1] = "Moe"; // stooges.length is 2 stooges[4] = "Curly"; // stooges.length is 5 stooges[4] = "Shemp"; // stooges.length is 5
length property (grows as needed when elements are added)var a = ["Stef", "Jason"]; // Stef, Jason a.push("Brian"); // Stef, Jason, Brian a.unshift("Kelly"); // Kelly, Stef, Jason, Brian a.pop(); // Kelly, Stef, Jason a.shift(); // Stef, Jason a.sort(); // Jason, Stef
split and join
var s = "the quick brown fox";
var a = s.split(" "); // ["the", "quick", "brown", "fox"]
a.reverse(); // ["fox", "brown", "quick", "the"]
s = a.join("!"); // "fox!brown!quick!the"
split breaks apart a string into an array using a delimiter
/:
var a = s.split(/[ \t]+/);
join merges an array into a single string, placing a delimiter between themnull and undefined
var ned = null;
var benson = 9;
var caroline;
// at this point in the code,
// ned is null
// benson's 9
// caroline is undefined
undefined : has not been declared, does not existnull : exists, but was specifically assigned an empty or null valueEvery Javascript program can refer to the following global objects:
| name | description |
|---|---|
document
|
current HTML page and its content |
history
|
list of pages the user has visited |
location
|
URL of the current HTML page |
navigator
|
info about the web browser you are using |
screen
|
info about the screen area occupied by the browser |
window
|
the browser window |
window objectthe entire browser window; the top-level object in DOM hierarchy
window objectdocument,
history,
location,
name
alert,
confirm,
prompt (popup boxes)
setInterval,
setTimeout
clearInterval,
clearTimeout (timers)
open,
close (popping up new browser windows)
blur,
focus,
moveBy,
moveTo,
print,
resizeBy,
resizeTo,
scrollBy,
scrollTo
window.open
window.open("http://foo.com/bar.html", "My Foo Window",
"width=900,height=600,scrollbars=1");
window.open pops up a new browser windowdocument objectthe current web page and the elements inside it
anchors,
body,
cookie,
domain,
forms,
images,
links,
referrer,
title,
URL
getElementByIdgetElementsByName,
getElementsByTagName
querySelector,
querySelectorAll
close,
open,
write,
writeln
location objectthe URL of the current web page
host,
hostname,
href,
pathname,
port,
protocol,
search
assign,
reload,
replace
navigator objectinformation about the web browser application
appName,
appVersion,
browserLanguage,
cookieEnabled,
platform,
userAgent
navigator object to see what browser is being used, and write browser-specific scripts and hacks:
if (navigator.appName === "Microsoft Internet Explorer") { ...
screen objectinformation about the client's display screen
availHeight,
availWidth,
colorDepth,
height,
pixelDepth,
width
history objectthe list of sites the browser has visited in this window
length
back,
forward,
go
history properties, for security<button onclick="okayClick();">OK</button>
// called when OK button is clicked
function okayClick() {
alert("booyah");
}
objectName.onevent = function;
<button id="ok">OK</button>
var okButton = document.getElementById("ok");
okButton.onclick = okayClick;
<html> <head> <script src="myfile.js" type="text/javascript"></script> </head> <body> ... </body> </html>
var x = 3;
function f(n) { return n + 1; }
function g(n) { return n - 1; }
x = f(x);
script tag
body
<html> <head> <script src="myfile.js" type="text/javascript"></script> </head> <body> <div><button id="ok">OK</button></div>
var ok = document.getElementById("ok");
ok.onclick = okayClick; // error: null
head is processed before page's body has loaded
window.onload event
function functionName() {
// code to initialize the page
...
}
// run this function once the page has finished loading
window.onload = functionName;
window.onload event that occurs at the moment the page body is done being loadedwindow.onload, it will run at that time
<button id="ok">OK</button> <!-- (1) -->
// called when page loads; sets up event handlers function pageLoad() { var ok = document.getElementById("ok"); // (3) ok.onclick = okayClick; } function okayClick() { alert("booyah"); // (4) } window.onload = pageLoad; // (2)
window.onLoad= pageLoad; window.onload = pageLoad;
() when attaching the handler ok.onclick = okayClick(); ok.onclick = okayClick;
alert; must enclose in your own function
ok.onclick =alert("booyah");ok.onclick = okayClick; function okayClick() { alert("booyah"); }
function okayClick() {
this.style.color = "red";
this.className = "highlighted";
}
.highlighted { color: red; }
function(parameters) {
statements;
}
window.onload = function() {
var ok = document.getElementById("ok");
ok.onclick = okayClick;
};
function okayClick() {
alert("booyah");
}
window.onload = function() {
document.getElementById("ok").onclick = function() {
alert("booyah");
};
};
These two function declarations are exactly equivalent:
function foo() {
// ...
}
var foo = function() {
// ...
};
In both cases JavaScript stores the function as an object, which can be passed around like any other variable:
var bar = foo;
// the following runs the same function twice
foo();
bar();
function foo() { ... }
var bar = foo; // foo IS NOT executed
// (assigned to another variable)
executeFunction(bar); // bar IS NOT executed yet
// (passed as a parameter)
foo(); // foo IS executed (parentheses added)
function executeFunction(fn) { // bar accepted as a parameter
// (NOT executed yet)
fn(); // bar (i.e., foo) IS executed (parentheses added)
}
() are added is a function actually executed
function gandalf(verb) {
alert("You shall not: " + verb.toUpperCase());
}
function runFunction(func, value) {
func(value); // calls whichever function is passed, passing value as a parameter
}
runFunction(gandalf, "pass!!!!!"); // 'You shall not: PASS!!!!!'
runFunction(function(meaning) {
alert("The meaning of life is: " + meaning); // 'The meaning of life is: 42'
}, 42);
var count = 0;
function incr(n) {
count += n;
}
function reset() {
count = 0;
}
incr(4);
incr(2);
console.log(count);
count, incr, and reset
function everything() {
var count = 0;
function incr(n) {
count += n;
}
function reset() {
count = 0;
}
incr(4);
incr(2);
console.log(count);
}
everything(); // call the function to run the code
everything (can we get it down to 0?)
(function() {
statements;
})();
(function() {
var count = 0;
function incr(n) {
count += n;
}
function reset() {
count = 0;
}
incr(4);
incr(2);
console.log(count);
})();