Some Information about Core JavaScript
JavaScript is pretty much the "only game in town" when it comes to client-side computation and web page interactivity. Certainly these days it is by far the most widely used tool for such things. This is in sharp contrast to the situation on the server side, where there are many competing alternatives. The notes on this page deal with the core language. A separate page discusses the DOM and client-side JavaScript.
See these sample files for illustrations of many of the concepts summarized here, and more.
Window
called
window
, which serves as a reference to the window
displaying the current document). Note that window
"owns" all global variables, including ones you declare, which are
accessible by all scripts associated with the given web page.Document
called
document
, which serves as a reference to the document
currently being displayed.head
element or the body
element of the web page, the
containing element will have script
element that looks
like this:
<script type="text/javascript"> ... code here for browser instruction ... document.write("Hello, world!"); //for example </script>In the case where the script is in an external file (
script.js
, say), a script
element that looks
like this will appear at the appropriate location in the web page markup:
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript"> <!-- document.write("Hello World!"); //--> </script>
For debugging JavaScript, make use of whatever debugging facilities are available, such as the Error Console under the Tools menu in Firefox, or the various features provided by the Firebug add-on to Firefox, for example.
There are two types of comments in JavaScript:
//
for single-line comments, or end-of-line
comments/* ... */
for multi-line commentsJavaScript is case-sensitive, but some aspects of (X)HTML and CSS are not, so be especially careful when mixing markup, styles and code.
Each JavaScript statement should be terminated by a semi-colon (;). This is not strictly necessary, provided each statement is on a separate line, but why tempt fate?
Braces (that is, the { and } symbols) group JavaScript statements into a compound statement. However, JavaScript does not have block scope, though it does have function scope.
Here is a table of the primitive data types in JavaScript, which are
somewhat like the primitive types in Java or C++, with the notable
exception that String
is regarded as a primitive type, and
there is no "single character" type.
Type | Value(s) | Wrapper Object | Other Values |
---|---|---|---|
Number |
double-precision floating-point | Number |
NaN ,Infinity ,-Infinity |
String |
single or double quotes | String |
\' , \" , \\ ,
"" , '' |
Boolean |
true , false |
Boolean |
0 , null , undefined ,
"" , '' ,and NaN are all false |
Undefined |
undefined |
N/A | N/A |
Null |
null |
N/A | N/A |
Here is a list of JavaScript operators:
+ - * / %
++ --
== != === !==
< <= > >=
&& || !
=
, as
well as += *=
, etc.? :
+
typeof
operator:
typeof x
returns
number
|string
|boolean
|object
,
depending on the type of x
.typeof(x)
.instanceof
operator:
someObjectVariable instanceof SomeObjectType
returns true
or false
, depending whether
the given object has the given type.Notes:
/
is not integer division in
JavaScript.===
and !==
should be preferred over
==
and !=
because they test for exact
equality (that is for both value and type) while == and !=
only test for value, and may also cause type coercion in a way that
makes the test misleading)Here are the basic type coercion/conversion rules for deciding what type a result will have when values of different types are involved in an expression that produces the result:
number+string
or string+number
gives a
string result.number op string
, string op number
,
string op string
all give a numerical result if
op
is -
, *
, or /
and string is in fact a number, otherwise the result is
NaN
.Number(string)
and String(number)
perform
the indicated conversions.numericalValue.toString()
.JavaScript has selection constructs analogous to those of Java, C and
C++, except that the switch
-statement permits the use of
string values:
if (condition) statement if (condition) statement1 else statement2 if (condition1) statement1 else if (condition2) statement2 else if (condition3) ... else default_statement switch (expression) { case value1: statement1 break; case value2: statement2 break; case value3: //Multiple values can cause the same action case value4: statement_for_either break; ... default: default_statement }
Note that any "statement" in any of the above patterns can be replaced by a compound statement (several statements enclosed in braces).
JavaScript has looping constructs analogous to those of Java, C and C++:
for (initialization; condition; update) statement while (condition) statement do statement while (condition);
Notes:
break;
statement in the body of a loop causes the
loop to be terminated at that point and execution to continue with the
next statement following that loop.continue;
statement in the body of a loop causes
the current loop iteration to terminate and execution to return to the
"top" of the loop and carry on with the next iteration.JavaScript function syntax looks like this:
function name([par_1, par_2, ..., par_n]) //parameters are optional { statement(s) [return value; | return expression;] //return statement optional }
Notes:
arguments
containing its arguments.var someVariable; //Declaration without initialization (value is undefined) var someVariable = someValue; //Declaration with initialization
var
keyword) and is global, even if inside a function.
someVar = someVal;
undefined
.Some built-in JavaScript objects:
All objects in JavaScript are specializations of a root object called
Object
. A variable of an object data type in JavaScript is
analogous to a reference in Java or a pointer in C++. The syntax for
access is also similar, as in myObject.property
or
myObject.method()
.
Number
Math
String
Array
Date
RegExp
See the relevant examples on thesample files page for much more detail on each of these objects.
Some built-in globals, all of which belong to the window
object (as do all programmer-defined variables/objects and
functions):
undefined Infinity NaN isNaN() Number() String() parseFloat() parseInt() alert(message) confirm(message) prompt(message[,defaultResponse]) setInterval(codeToExecute,numberOfMilliseconds) clearInterval(referenceReturnedFrom_setInterval) setTimeout(codeToExecute,numberOfMilliseconds) clearTimeout(referenceReturnedFrom_setTimeout)
var
when declaring variables, and put all
variables declared in a function at the beginning of the function.\
just before the return character, though it should be regarded as a
"best practice" not to do so, and use the +
operator to
concatenate the necessary strings instead.undefined
.var
is global,
even if declared inside a function.if (date1 == date2) { ... }
if (date1.getTime() == date2.getTime()) { ...
}
eval()
that takes a string as
input and attempts to evaluate it as JavaScript code. Doing this should
be avoided as it represents a security problem.