Core JavaScript Notes

The bulk of these notes were taken from/while reading through JavaScript: The Definitive Guide (5th edition) by David Flanagan. Copyright 2006 O'Reilly Media, Inc., 978-0-596-10199-2. Some lines are copied verbatim, but generally, they are 'paraphrased' for better 'personal referencability'. Quoted items are generally linked back to this paragraph. Some other notes were taken from other sources available on the Internet. This document is intended primarily for personal reference.

Table of Contents


Basic use of JavaScript

<!--include one of the following at the beginning of your doc
to force IE6+ into standards mode-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Strict//EN">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<head>
<meta http-equiv="Content-Script-Type" content="text/javascript"> <!--set default script type-->

<script src="path/util.js"></script>				  <!--external file-->
<script src="path/util.js type="text/javascript" language="JavaScript"></script>

<script>//javascript goes here<script>			   	  <!--embedded version simple-->

<script type="text/javascript" language="JavaScript">		  <!--embedded version descriptive-->
// JavaScript goes here						  <!--future will be-->
</script>							  <!--type="application/javascript"-->

<script><![CDATA[						  <!--XHTML ver of script tag-->
// JavaScript goes here
]]></script>

<script defer><!--JavaScript here--></script>			  <!--IE runs script at end of doc-->
<script defer="defer"><!--JavaScript here--></script>		  <!--XHTML version of the same-->
<!--attach event handler to DOMContentLoaded-->			  <!--firefox defer technique 
										(undocumented)-->
<script><!-- Old browsers don't recognize <script> tags
// use html comments above to hide Javascript here
// No longer needed --></script>
</head>
<body>
<noscript>
This displays if JavaScript has been disabled.
</noscript>
...
<script>
// single-line comment
/* multi
   line
   comment */
var num=1;  // comment after the line
for(i = 1; i < 10; i++) {
	num = num + num;
	document.write("i: " + i + ", num: " + num + "<br />");
}
document.write("you may have to write </" + "script> or maybe &lt;/script&gt;");

</script>
...
</body>

Initial notes

Literals

12, 1.2, "hello world", 'Hi', true, false, /blah/gi (regular expression for patern matching), null
{ a:5, b:2 } - object initializer
[1,2,3,4,5] - array initializer

Arithmatic ops

Special Constants

InfinityWhen floating point value gets larger then largest representable finite number
NaN(Not-a-Number) - Undefined result or an error
Number.MAX_VALUE
Number.MIN_VALUE
Number.NaN
Number.POSITIVE_INFINITY
Number.NEGATIVE_INFINITY
nullvariable does not conatain a valid object, array, nujmber, string, or boolean value. Converts to false in a boolean context. Converts to "null" in a string context. Converts to 0 in a numeric context.
undefineda var that has been declared but has no value assigned to it, or an object property that does not exist. You can also get the undefined value using the void operator. Equality operator (==) says it is equal to null. Identity operator (===) does not.


Strings

String escape sequences

\0The NUL character
\bbackspace
\thorizontal tab
\nnewline
\vvertical tab
\fform feed
\rcarriage return
\"double quote
\'single quote/apostrophe
\\backslash
\xXXchar specified by 2 hex digits
\uXXXXunicode char specified by 4 hex digits
\XXXchar specified by 3 octal digits. not supported in ECMAScript v3

Working with Strings

word = "up"
datext = "What's " + word + "?" 
document.write(datext + "<br />");
document.write(datext.length + "<br />");

lastchar = datext.charAt(datext.length - 1)
document.write(lastchar + "<br />");
sub = datext.substring(2,6)
document.write(sub + "<br />");
posoffirstlettera = datext.indexOf('a')
document.write(posoffirstlettera + "<br />");


In some versions of Javascript, individual chars can be read from strings (but not written) using array notation - not standard should be avoided
lastchar = datext[datext.length - 1]

Numbers to Strings

var n = 100;
var s = n + " bottles of beer on the wall.";
var nstring = n + "";
var nstring = String(n); //better
nstring = n.toString();
var n = 17
document.write(n.toString(2) + " "); // Binary
document.write(n.toString(8) + " "); // Octal
document.write(n.toString(16) + " "); // Hex

Strings to Numbers

var product = "21" * "2";
document.write(product + "<br />");
var number = "42" - 0; // auto-converts string to num - adding results in string concat
var number = Number("3.14");


Functions

function multiply(x, y)
{
  return x*y;
}
function doublesquare(a, b)
{
  function double (x) { return 2*x } //nested function
  return (double(a) * double(b));
}
document.write(multiply(5, 6));
document.write("<br />");
document.write(multiply(3, 2)/multiply(2,2));
document.write("<br />");
document.write(doublesquare(3,4));

Function Literals (i.e. inline functions)

function f(x) { return x+x; } //is the same as
var f = function(x) { return x+x; };

Optional Arguments

function defadd(a, b) {
  if (!a) a = 2; //assign default val to a if not passed
  b = b || 3;    //assign default val to b if not passed
  return(a+b);
}
document.write(defadd(10,20) + "<br />");
document.write(defadd(10) + "<br />");
document.write(defadd() + "<br />");
document.write(defadd(undefined,20) + "<br />");
document.write(defadd(null,21) + "<br />");

Variable-length arg lists: Arguments Object

function addemall(x) {
  var m = 0;
  document.write("changing " + x);
  x = x + 1;
  arguments[0] = arguments[0] + 1;
  document.write(" to " + x + "<br />");
  for (var i = 0; i < arguments.length; i++)
    m = m + arguments[i];
  return m;
}
function writethevars() {
  var datype;
  for(var i=0; i < arguments.length; i++) {
    datype = typeof arguments[i];
    document.write("arg " + i + " is of type " + datype);
    document.write(" with a value of " + arguments[i] + "<br />");
  }
}
document.write(addemall(10,20,2) + "<br />");
writethevars(333,"balloons",true);

Callee function

function multdown(y) {
  if (y <= 1) return 1;
  return y * arguments.callee(y-1); // callee function refers to function being executed
}
document.write(multdown(4));

object props as args

function damaththing(args) {
  args.x = args.x || 3;
  args.y = args.y || 2;
  return (args.x + args.y);
}
document.write(damaththing({x: 5, y: 6}) + "<br />");
document.write(damaththing({y: 20}));

functions as syntax and/or data

function addit(x,y) { return x+y };
function subit(x,y) { return x-y };

function oper(daoper, arg1, arg2) { 
  return daoper(arg1, arg2) 
}

function oper(daoper, arg1, arg2) { 
  return daoper(arg1, arg2) 
}

document.write(oper(addit,"hi ","there "));
document.write(oper(subit,7,4));

//------------------

var obj1 = {
  write: function(a) { document.write("<br />this is a "+ a + "<br />"); },
  add:   function(b,c) { return b + c; }
}
function callobj1(dafunc,arg1,arg2) {
  return(obj1[dafunc](arg1,arg2));
}
  
obj1.write("function in a object");
document.write(callobj1("add",5,11));

Functions as methods and the 'this' keyword

'this' refers to current function
var double = {
  var1: 2,
  compute: function(daval) {
    this.result = daval * this.var1;
  }
};
double.compute(4);
document.write(double.result);

function properties

function.lengthreturns the number of parameters the function expects to be passed (i.e. what's declared)
function.prototypeIs this part of the prototype for this function

increment.counter = 0;
function increment() { 
  document.write(increment.counter++); // global function var/property kept
  document.write("<br />");
}
increment();
increment();
increment();

Function() constructor

var f = new Function("x", "y", "return x*y;")
  is the same as
function f(x, y) { return x*y; }

apply() and call()

function f22(x, y) {return x*y;}

//document.write(f22.call(o, 1, 2));
document.write(f22.call(o, 1, 2) + "<br />");
document.write(f22.apply(o, [2,2]) + "<br />");
// same as
var o = {x:4, y:5};
o.m = f22;
document.write(o.m(3,2));
delete o.m;

Invoking a function without cluttering global namespace

(function() { // this function has no name
  var v = 1;
  document.write("v = " + v);
})(); //parens around function invokes is


Closures

Objects

var blah = new Object();
blah.x = 5;
blah.y = 6
document.write(blah.x+blah.y);
var now = new Date();
var pattern = new RegExp("\\sthing\\s", "i");
var blah2 = { x:2, y:6 };
var blah3 = { point1: { x: 2, y: 3 },
              point2: { x: 4, y: 5 }
            }
document.write(blah3.point2.x);

Date object

var now = new Date(); // creates an object holding current date and time
var dadate = new Date(2007, 12, 04);
dadate.setFullYear(dadate.getFullYear() + 1);
var weekday = dadate.getDay();
document.write("The day is "+ now.toLocaleStrint()); //curr date/time

Enumerating Properties

function DispPropNames(obj) {
	for(var name in obj) 
		document.write(name + ": " + obj[name] + "<br />");
	for(i = 1; i < 4; i++)	
		document.write("x" + i + ": " + obj["x" + i] + "<br />");
}
var blah77 = {x: "hello", y: "151", z: "goodbye"};
DispPropNames(blah77);

Checking for Property Existence

if ("x" in o) o.x = 1;
// !== and === distinguish betwen undefined and null.
if (o.x !== undefined) o.x = 1;
if (o.doSomething) o.doSomething();

Universal Properties

constructor
refers to the constructor function that initializes the object
var d = new Date();
d.constructor == Date; //Evaluates to true;
if ((typeof o == "object") && (o.constructor == Date))

if ((typeof o == "object") && (o instanceof Date))
toString()
works with any object...
<pre>
<script>
function hithere() {
	document.write("hi there");
}
document.write(hithere.toString());
</script>
</pre>

other universal properties
toLocalString()return a localized string representation of the object
valueOf()like toSTring(), but converts to primitive, typically a number
hasOwnProperty()returns true if not an inherited property
propertyIsEnumerablenoninherited property, name is a single string, would be enumeriated by a for/in loop.
var blah88 = {x:1, y:2};
if (blah88.propertyIsEnumerable("y") document.write("true<br />");
if (blah88.propertyIsEnumerable("valueOf") document.write("true again<br />");
isPrototypeOf()true if method attached is the prototyp object of the arg

Contructors & Prototypes

function Rectangle(w, h) {
  this.width = w;
  this.height = h;
}
//Add after constructor above
//this creates a instance method?
Rectangle.prototype.area = function() { return this.width * this.height; }
//this creates a instance property?
Rectangle.prototype.commvar = 1;
//this creates a class property
Rectangle.uniquevar = 2;
//this creates a class method
Rectangle.biggerwidth = function(a, b) {
  if (a.width > b.width) return(a);
  else return(b);
}

var r = new Rectangle(3, 4);
document.write("r.area - " + r.area() + "<br />");
document.write("r.commvar - " + r.commvar + "<br />");
r.commvar++;
document.write("r.commvar - " + r.commvar + "<br />");
var multvar = r.commvar * Rectangle.uniquevar;
document.write("multvar - " + multvar + "<br />");
var r2 = new Rectangle(5, 6);
var biggerwidthrect = Rectangle.biggerwidth(r, r2);
document.write("Rectangle bigger width is " + biggerwidthrect.width + "<br />");

Common object methods

Consider creating the following methods for any custom object.

Superclasses and Subclasses

PositionedRectangle is a subclass of Rectangle above...
function PositionedRectangle(x, y, w, h) {
  //grab width and height from before
  //this is called constructor chaining
  Rectangle.call(this, w, h)
  //no grab upper-left corner position
  this.x = x;
  this.y = y;
}
//subclass Rectangle using prototype
PositionedRectangle.prototype = new Rectangle();
//delete the width and height properties from the inherited prototype?
delete PositionedRectangle.prototype.width;
delete PositionedRectangle.prototype.height;
//add a method to our subclass
PositionedRectangle.prototype.contains = function(x,y) {
  return (x > this.x && x < this.x + this.width && 
          y > this.y && y < this.y + this.height);
}
//try out the code
var rr = new PositionedRectangle(2,3,4,5);
document.write(rr.contains(3,3) + "<br />");
document.write(rr.area() + "<br />");
document.write(rr.x + ", " + rr.y + ", " + rr.width + ", " + rr.height + "<br />");
document.write(rr instanceof PositionedRectangle &&
      rr instanceof Rectangle &&
      rr instanceof Object);
document.write("<br />");

Could replace Rectangle.call above with:
//store a ref to superclass constructor
PositionedRectangle.prototype.superclass = Rectangle;
function PositionedRectangle(x, y, w, h) {
  this.superclass(w,h);
  this.x = x;
  this.y = y;
}

Invoking Overridden Methods

// if Rectangle had a toString method defined
Rectangle.prototype.toString = function() {
  return "[" + this.width + "," + this.height + "]";
}
//and you wanted to override and still augment/call the method from within
PositionedRectangle.prototype.toString = function() {
  return "(" + this.x + "," + this.y + ") " +
	Rectangle.prototype.toString.apply(this);
// OR if you've defined the superclass above...
//return "(" + this.x + "," + this.y + ") " +
//	this.superclass.prototype.toString.apply(this);
}

Copying methods

Since functions are data values of a class, it is possible to copy them from one method to another

Determining Object Type



Arrays

var zz = new Array();
zz[0] = 5.4;
zz[1] = "sleeping";
zz[2] = true; 
zz[3] = { x: 3, y: 2 };
var yy = new Array(9.8, "snoring", false, { x: 7, y: 6 });
document.write(zz[0] + " " + yy[1] + "<br />");
document.write("zz.length = " + zz.length + "<br />);
var matrix = [[9,8,7],[6,5,4],[3,2,1]];
document.write(matrix[1][2]); // array indexes start at 0
new xx = new Array(10); // 10 undefined elements
new ww = [6,,,,2]; // 3 empty elements in this one
var daarray = new Array(3); // length defined.  elements at this point are undefined
var veggies = ["carrots", "peas", "broccoli"]
for(var ii = 0; ii < veggies.length; ii++) 
	document.write(veggies[ii] + "<br />");
document.write(typeof veggies);

Quick ways to add to end of array

var blah = [
	'first entry',
	'second entry'
];
blah.push('third entry');
blah[links.length] = 'fourth entry'); // also pushes length to be one more...

Deleting

Array.shift()deletes first element
Array.pop()deletes last element
Array.splice()deletes contiguous range of elements from array

Truncating and Enlarging arrays

Array Methods

join()
Array.join(", ") //optional specify separator
returns all elements of array as a concatenated string
reverse()
Array.reverse()
reverses te order of the elements of the array
sort()
a.sort(function(a,b) {
  if ((a.substring(0,0) == "A") && (b.substring(0,0) != "A")) 
    return(-1); // anything w/ "A" goes to beginning
  else 
    return(0); // otherwise don't sort it
  });
  • sorts array elements in alphabetical order (by default). undefined elements get sorted tot he end.
  • can also put in sort function.
    • If 1st arg should appear before the 2nd, comparison function should return num <0.
    • If 2nd arg should appear before the 1st, comparison function should return num >0.
    • If args are equivalent, comparison function should return 0.
concat()
Array.concat(<elements>)
Array.concat(4,5)
  • returns a new array that contains orig array with arguments in concat appended.
  • Will flatten 1 level of elements (i.e. [4,5]), but not more (i.e. [4,[5,6]] will come through with [5,6] as an array element in the array.
slice()
Array.slice(<slice range>)
Array.slice(4,5)
  • returns a subarray specified by range
  • negative arguments specify range from end of array
splice()
Array.splice(<beginning position>, [<number of elements>],[<arg1 to insert>,<arg2 to insert>,...])
var ab = [10,20,30,40,50,60,70,80];
bb = ab.splice(5);
document.write("bb - " + bb + ", ab - " + ab + "<br />");
bb = ab.splice(1,2);
document.write("bb - " + bb + ", ab - " + ab + "<br />");
bb = ab.splice(2,0,95,96);
document.write("bb - " + bb + ", ab - " + ab + "<br />");
bb = ab.splice(2,2,[97,98],99);
document.write("bb - " + bb + ", ab - " + ab + "<br />");
  • Removes range from array, and returns range removed.
  • If 2nd arg is omitted, it defaults to end of array.
push(), pop()
Array.push(<element(s)>)
Array.pop([<numberofelements>])
push or pop elements onto the end of the array like a stack
unshift(), shift()like push() and pop(), but puts stuff on beginning of array
toString(), toLocalString()comma separated list

Values by Reference and by Value

Vars

Interesting Operators

<<left shift
>>right shift with sign extension
>>>Right shift with zero extension
instanceofCheck object type
var d = new Date();
d instanceof Date; // true
d instanceof Number; //false
inCheck whether property exists. Left-side operand is or can be converted to a string. right-side operand that is an object or array.
var dot = { x:1, y:2 };
var davalue = "x" in point; // evaluates to true
var daothervalue = "z" in point; //evaluates to false; there is no z property
==Tests for equality
!=Tests for inequality
===Tests for identity
!==Tests for non-identity
?:Conditional operator (3 operands) (example x > 0 ? x*y : -x*y)
,Multiple evaluation (x = 0, y = 1, z = 2
^bitwise XOR
~bitwise NOT (unary)
!logical complement (unary)
deleteundefine a property (unary)
var xyz = {x:1, y:2};
delete xyz.x; // delete one of the object properties
delete xyz; // can't delete declared vars only var/object properties
x = 1; // implicit declaration
delete x; // this will work
var dadate = new object();
dadate.date1 = new Date();
dadate.date2 = dadate.date1;
delete dadate.date1; // delete property date1
document.write(dadate.date2); // this will work because the object still exists
voidreturn undefined value (unary) (Example <a href="javascript:void window.open();">Open New Window</a>)
typeofReturn datatype (unary). Evaluates to number, string, boolean, function, undefined, or object (for objects, arrays, and null).

Equality and Identity

Interesting String stuff

s = 1 + 2 + " balloons"; // yields "3 balloons"
t = "balloons " + 1 + 2; // yields "ballons 12"

Statements

the following table is taken directly from JavaScript: The Definitive Guide (5th edition) by David Flanagan.
StatementSyntaxPurpose
breakbreak;
break label
casecase expression:within a switch statement
continuecontinue;
continue label;
restart innermost loop or or loop named label
defaultdefault:default statement in a switch statement
do/whiledo
statement
while (expression);
empty;do nothing
forfor (initialize ; test ; increment)
statement
for/infor (variable in object)
statement
loop through object properties
functionfunction funcname([arg1[..., argn]])
{
statements
}
function declaration
if/elseif (expression)
statement1
[else statement2]
labelidentifier: statementgive statement the name identifier
returnreturn[expression];exit a function possibly with the value expression
switchswitch (expression) {
statements
}
multiway branch to statements labeled with case or default:
throwthrow expression;Throw an exception
trytry {
statements
}
catch (identifier) {
statements
}
finally {
statements
}
catch an exception
varvar name_1 [ = value_1]
[ ,..., name_n [ = value_n]];
declare and init vars
whilewhile (expression)
statement
withwith (object)
statement
extend scope chain (deprecated)

Modules and Namespaces

Regular Expressions

Basics

var pattern = /s$/;              //look for something that ends with s
var pattern = new RegExp("s$");
/[abc]/		//matches any one of the letters a, b, c
/[^abc]/	//matches any one char other then a, b, c
/[a-z]/		//match any lowercase letter or digit in the latin alphabet

String & Regexp methods

Stringsearch()returns char position of start of matching substring or -1 if no match
"Blahtext".search(/text/i) returns 4
replace()matches 1st argument, and replaces with second argument

var datext="Blahtext is something that blahtext can't stand";
var datext2 = datext.replace(/Blahtext/gi,"BlahText"); //replaces all instances of blahtext with capitalized
document.write(datext + "<br />");
document.write(datext2 + "<br />");
match()matches arguments and returns them into an array.
  • with non-global search array[0] includes entire match, array[1] includes 1st paren expression, and so on
  • .index will include char position where match began.
  • .input includes copy of string.

var daarray99 = "4 and 20 blackbirds backed 36 pies".match(/\d+/g);
for (i = 0; i < daarray99.length; i++)
	document.write(daarray99[i] + "<br />");
var url = /(\w+):\/\/([\w.]+)\/(\S*)/;
var daarray100 = "http://dhtmlsite.com/ajax.php".match(url);
for (i = 0; i < daarray100.length; i++)
	document.write(daarray100[i] + "<br />");
split()breaks string into array of strings around delimiter
var daarray101 = "abc, def,geh ,ikj , lmn".split(/\s*,\s*/);
for (i = 0; i < daarray101.length; i++)
	document.write(daarray101[i] + "-");
RegExpexec()like string match above, except it always returns a single match. With the g flag set, .lastIndex is char pos following the matched substring (so you can rerun the match from there). .lastIndex goes to 0 when no more matches are found a9or you can set it to quit the search early).

var text102 = "blah2 is after blah or the initial blah0";
var pattern102 = /blah\d*/g;
var result102 = pattern102.exec(text102);
document.write(result102 + " - " + pattern102.lastIndex);
var result102 = pattern102.exec(text102);
document.write(" - " + result102 + " - " + pattern102.lastIndex);
test()returns true if string contains a match for reg expression. Uses .lastIndex the same way as exec()

var pattern103 = /blah/i;
document.write(pattern103.test("this blah text");

Literal chars

this table taken from table 11-1 in JavaScript: The Definitive Guide (5th edition) by David Flanagan. Copyright 2006 O'Reilly Media, Inc., 978-0-596-10199-2.
CharMatches
Alphanumeric charitself
\0The NUL char (\u0000)
\tTab (\u0009)
\nNewline (\u000A)
\vVertical tab (\u000B)
\fForm feed (\u000C)
\rCarriage Return (\u000D)
\xnnLatin char specified by hex #
\uxxxxUnicode char specified by hex number
\cXcontrol char (i.e. \cJ is control-j (newline))

Char Classes & Word Boundaries

this table taken from tables 11-2 and 11-5 in JavaScript: The Definitive Guide (5th edition) by David Flanagan. Copyright 2006 O'Reilly Media, Inc., 978-0-596-10199-2.
charmatches
[...]any one char between brackets
[^...]any one char not between brackets
.any char except newline or another Unicode line terminator
\w[a-zA-Z0-9_]
\W[^a-zA-Z0-9_]
\swhitespace
\Sany char that is not whitespace
\d[0-9]
\D[^0-9]
[\b]backspace
^beginning of the string, beginning of a line
$end of the string, end of a line
\bword boundary (i.e. between \w and \W, or between \w and beginning or end of string
/\bhello\b/ matches hello at the beginning or end of a line, or in the middle of a sentence
\Bnot a word boundary
/\Bhello/ matches Wellhello but not hello
(?=p)positive lookahead assertion - only matches if exists, but doesn't match
/hello(?=:)/ matches 'hello: how to say hi', but doesn't match 'hello - how to say hi'
(?!p)negative lookahead assertion - only matches if doesn't exist
/hello(?!:)/ doesn't match 'hello: how to say hi', but does match 'hello - how to say hi'

Repetition

the following table taken from table 11-3 in JavaScript: The Definitive Guide (5th edition) by David Flanagan. Copyright 2006 O'Reilly Media, Inc., 978-0-596-10199-2.
charmeaning
{n,m}match previous item n to m times
{n,}match previous item n or more times
{n}match exactly n occurrences of previous item
?{0,1} (i.e. optional)
+{1,} (i.e. one or more)
*{0,} (i.e. 0 or more)

Alternation, Grouping, and References

the following table taken from table 11-4 in JavaScript: The Definitive Guide (5th edition) by David Flanagan. Copyright 2006 O'Reilly Media, Inc., 978-0-596-10199-2.
charmeaning
|match either expression to left OR right
(...)group items into single unit, and remember for later references
(?:...)group items into single unit, but do not remember for later reference
\nmatch the same item that was matched in group n

examples...
/(ab|cd)/		//matches ab or cd
/(['"])([^'"]*)\1/	//matches a string that begins and ends with the same type of quote (' or ")
			//for ref, /2 matches the string, and the string doesn't have any quotes in it
(?:\+|%2B|%2b)(1\d\d\d\d\d\d\d\d\d\d)
			//match + in any of it's forms but don't remember it
			//then match a 1 followed by 10 digits (and remember it)

Flags