Javascript: Language Fundamentals
Javascript: Language Fundamentals
Language Fundamentals
3
JavaScript isn’t always available
Some old browsers do not recognize script tags
These browsers will ignore the script tags but will display the included
JavaScript
To get old browsers to ignore the whole thing, use:
<script type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
The <!-- introduces an HTML comment
To get JavaScript to ignore the HTML close comment, -->, the // starts a
JavaScript comment, which extends to the end of the line
Some users turn off JavaScript
Use the <noscript>message</noscript> to display a message in place of
whatever the JavaScript would put there
4
Where to put JavaScript
JavaScript can be put in the <head> or in the <body> of an
HTML document
JavaScript functions should be defined in the <head>
This ensures that the function is loaded before it is needed
6
Semicolons
Unlike PHP, JavaScript generally does not require
semicolons if you have only one statement on a line.
Therefore, the following is valid:
x += 10
However, when you wish to place more than one
statement on a line, you must separate
them with semicolons, like this:
x += 10; y -= 5; z = 0
You can normally leave the final semicolon off, because
the newline terminates the final statement.
7
Primitive data types
JavaScript has three “primitive” types: number, string, and
boolean
Everything else is an object
Numbers are always stored as floating-point values
Hexadecimal numbers begin with 0x
Some platforms treat 0123 as octal, others treat it as decimal
Since you can’t be sure, avoid octal altogether!
Strings may be enclosed in single quotes or double quotes
Strings can contains \n (newline), \" (double quote), etc.
Booleans are either true or false
0, "0", empty strings, undefined, null, and NaN are false , other
values are true
8
Variables
10
To read from a string variable, you can assign it to
another one, like this:
newstring = oldstring
or you can use it in a function, like this:
status = "All systems are working"
document.write(status)
11
Numeric Variables
Creating a numeric variable is as simple as assigning a
value, like these examples:
count = 42
temperature = 98.4
Like strings, numeric variables can be read from and
used in expressions and functions.
12
Operators, I
Because most JavaScript syntax is borrowed from C (and is
therefore just like Java), we won’t spend much time on it
Arithmetic operators (all numbers are floating-point):
+ - * / % ++ --
Comparison operators:
< <= == != >= >
Logical operators:
&& || ! (&& and || are short-circuit operators)
Bitwise operators:
& | ^ ~ << >> >>>
Assignment operators:
+= -= *= /= %= <<= >>= >>>= &= ^= |=
13
Operators, II
String operator:
+
The conditional operator:
condition ? value_if_true : value_if_false
Special equality tests:
== and != try to convert their operands to the same type
before performing the test
=== and !== consider their operands unequal if they are of
different types.
14
Comments
Comments are as in C or Java:
Between // and the end of the line
Between /* and */
Java’s javadoc comments, /** ... */, are treated just the
same as /* ... */ comments; they have no special
meaning in JavaScript
15
Statements, I
16
Statements, II
The switch statement:
switch (expression) {
case label :
statement;
break;
case label :
statement;
break;
...
default : statement;
}
Other familiar statements:
break;
continue;
The empty statement, as in ;; or { }
17
JavaScript is not Java
By now you should have realized that you already know a
great deal of JavaScript
So far we have talked about things that are the same as in Java
JavaScript has some features that resemble features in Java:
JavaScript has Objects and primitive data types
JavaScript has qualified names; for example,
document.write("Hello World");
JavaScript has Events and event handlers
Exception handling in JavaScript is almost the same as in Java
JavaScript has some features unlike anything in Java:
Variable names are untyped: the type of a variable depends on the
value it is currently holding
Objects and arrays are defined in quite a different way
JavaScript has with statements and a new kind of for statement
18
Object literals
You don’t declare the types of variables in JavaScript
JavaScript has object literals, written with this syntax:
{ name1 : value1 , ... , nameN : valueN }
special
"Saturn" and "Mazda" are Strings
19
Three ways to create an object
You can use an object literal:
var course = { number: "CIT597", teacher: "Dr. Dave" }
You can use new to create a “blank” object, and add fields to it
later:
var course = new Object();
course.number = "CIT597";
course.teacher = "Dr. Dave";
You can write and use a constructor:
function Course(n, t) { // best placed in <head>
this.number = n; // keyword "this" is required, not optional
this.teacher = t;
}
var course = new Course("CIT597", "Dr. Dave");
20
Array literals
You don’t declare the types of variables in JavaScript
JavaScript has array literals, written with brackets and
commas
Example: color = ["red", "yellow", "green", "blue"];
Arrays are zero-based: color[0] is "red"
If you put two commas in a row, the array has an
“empty” element in that location
Example: color = ["red", , , "green", "blue"];
color has 5 elements
However, a single comma at the end is ignored
Example: color = ["red", , , "green", "blue”,]; still has 5 elements
21
Four ways to create an array
You can use an array literal:
var colors = ["red", "green", "blue"];
You can use new Array() to create an empty array:
var colors = new Array();
You can add elements to the array later:
colors[0] = "red"; colors[2] = "blue"; colors[1]="green";
You can use new Array(n) with a single numeric
argument to create an array of that size
var colors = new Array(3);
You can use new Array(…) with two or more arguments
to create an array containing those values:
var colors = new Array("red","green", "blue");
22
The length of an array
23
Arrays and objects
Arrays are objects
car = { myCar: "Saturn", 7: "Mazda" }
car[7] is the same as car.7
car.myCar is the same as car["myCar"]
If you know the name of a property, you can use dot
notation: car.myCar
If you don’t know the name of a property, but you have
it in a variable (or can compute it), you must use array
notation: car["my" + "Car"]
24
Array functions
If myArray is an array,
myArray.sort() sorts the array alphabetically
myArray.sort(function(a, b) { return a - b; }) sorts
numerically
myArray.reverse() reverses the array elements
myArray.push(…) adds any number of new elements to the
end of the array, and increases the array’s length
myArray.pop() removes and returns the last element of the
array, and decrements the array’s length
myArray.toString() returns a string containing the values of
the array elements, separated by commas
25
The for…in statement
You can loop through all the properties of an object with
for (variable in object) statement;
Example: for (var prop in course) {
document.write(prop + ": " + course[prop]);
}
Possible output: teacher: Dr. Dave
number: CIT597
The properties are accessed in an undefined order
If you add or delete properties of the object within the loop, it is
undefined whether the loop will visit those properties
Arrays are objects; applied to an array, for…in will visit the
“properties” 0, 1, 2, …
Notice that course["teacher"] is equivalent to course.teacher
You must use brackets if the property name is in a variable
26
The with statement
with (object) statement ; uses the object as the default
prefix for variables in the statement
For example, the following are equivalent:
with (document.myForm) {
result.value = compute(myInput.value) ;
}
document.myForm.result.value =
compute(document.myForm.myInput.value);
One of my books hints at mysterious problems resulting
from the use of with, and recommends against ever
using it
27
Functions
Functions should be defined in the <head> of an
HTML page, to ensure that they are loaded first
The syntax for defining a function is:
function name(arg1, …, argN) { statements }
The function may contain return value; statements
Any variables declared within the function are local to it
The syntax for calling a function is just
name(arg1, …, argN)
Simple parameters are passed by value, objects are
passed by reference
28
Regular expressions
A regular expression can be written in either of two ways:
Within slashes, such as re = /ab+c/
With a constructor, such as re = new RegExp("ab+c")
Regular expressions are almost the same as in Perl or Java (only
a few unusual features are missing)
string.match(regexp) searches string for an occurrence of
regexp
It returns null if nothing is found
If regexp has the g (global search) flag set, match returns an array of
matched substrings
If g is not set, match returns an array whose 0th element is the matched
text, extra elements are the parenthesized subexpressions, and the index
property is the start position of the matched substring
29
Warnings
JavaScript is a big, complex language
We’ve only scratched the surface
It’s easy to get started in JavaScript, but if you need to use it
heavily, plan to invest time in learning it well
Write and test your programs a little bit at a time
JavaScript is not totally platform independent
Expect different browsers to behave differently
Write and test your programs a little bit at a time
Browsers aren’t designed to report errors
Don’t expect to get any helpful error messages
Write and test your programs a little bit at a time
30
Evaluation (i.e., Dave’s opinion)
JavaScript, like Java, is in the C family of languages
JavaScript has lots of convenience features
Global variables
Not having to declare variables at all
Untyped variables
Easy modification of objects
JavaScript is designed for programming in the small, not for
large programs
Many features, such as global variables, are bad news for large programs
My experience is that JavaScript is very nice if you use it for the
purposes that its designers expected, but very ugly if you try to
use it in non-routine ways
31
The Document Object Model
JavaScript has a hierarchy of parent and child objects,
which is what is known as the Document Object Model
(DOM).
JavaScript separates objects, properties, and methods by
using a period. For example, let’s consider a business
card as an object we’ll call card.
This object contains properties such as a name, address,
phone number, and so on.
In the syntax of JavaScript, these properties would look
like this: card.name, card.phone, card.address
32
33
34
Printing to the screen
Document.write();
Console.log();
Alert();
35
EXPRESSIONS IN JAVASCRIPT
an expression is a combination of values, variables,
operators, and functions that results in a value.
36
Literals and Variables
The simplest form of an expression is a literal, which
means something that evaluates to itself, such as the
number 22 or the string Press Enter.
An expression could also be a variable, which evaluates
to the value that has been assigned to it.
They are both types of expressions, because they return
a value.
37
The with Statement
38
Conditionals
Conditionals alter program flow. They enable you to ask
questions about certain things and respond to the
answers you get in different ways.
There are three types of nonlooping conditionals: the if
statement, the switch statement, and the ? operator.
39
The if Statement
The code within such a statement is executed only if the
given expression evaluates to true.
Multiline if statements require curly braces around
them, but as in PHP, you can omit the braces for single
statements.
40
The else Statement
When a condition has not been met, you can execute an
alternative by using an else statement, like this:
41
Unlike PHP, JavaScript has no elseif statement, but
that’s not a problem because you
can use an else followed by another if to form the
equivalent of an elseif statement, like this:
42
The switch Statement
The switch statement is useful when one variable or the
result of an expression can have multiple values and you
want to perform a different function for each value.
43
SWITCH STATEMENT
44
Looping
while Loops
A JavaScript while loop first checks the value of an
expression and starts executing the statements within
the loop only if that expression is true.
If it is false, execution skips over to the next JavaScript
statement (if any).
45
46
for Loops
47
JavaScript Functions
In addition to having access to dozens of built-in
functions (or methods), such as write, which you have
already seen being used in document.write, you can
easily create your own functions.
Whenever you have a relatively complex piece of code
that is likely to be reused, you have a candidate for a
function.
48
Defining a Function
The general syntax for a function is shown here:
49
The arguments array
The arguments array is a member of every function.
With it, you can determine the number of variables
passed to a function and what they are.
50
51
JavaScript and PHP Validation
We’ll be using PHP to create the forms and JavaScript
to perform client-side validation
to ensure that the data is as complete and correct as it
can be before it is submitted.
Final validation of the input will then be done by PHP,
which will, if necessary,
present the form again to the user for further
modification.
52
Validating User Input with JavaScript
JavaScript validation should be considered an assistance
more to your users than to your websites because, you
cannot trust any data submitted to your server, even if it has
supposedly been validated with Java‐Script.
Another reason you cannot rely on JavaScript to perform all
your input validation is that some users disable JavaScript,
or use browsers that don’t support it.
The best types of validation to do in JavaScript are checking
that fields have content if they are not to be left empty,
ensuring that email addresses conform to the proper format,
and ensuring that values entered are within expected bounds
53
54
55
Between the <script> and </script> tags lies a single function
called validate that itself calls up six other functions to validate
each of the form’s input fields.
The functions return either an empty string if a field validates or
an error message if it fails.
Upon passing validation, the validate function returns a value of
true; otherwise, it returns false. The return values from validate
are important, because if it returns
false, the form is prevented from being submitted. This allows the
user to close the alert pop-up and make changes. If true is
returned, no errors were encountered in the form’s fields, and so
the form is submitted.
56
57
58
Using a separate JavaScript file
You could name the file something like
validate_functions.js and include it right after the initial
script section using the following statement:
59
Regular Expressions
Let’s look a little more closely at the pattern matching
we have been doing. We’ve
achieved it using regular expressions, which are
supported by both JavaScript and
PHP. They make it possible to construct the most
powerful of pattern-matching algorithms
within a single expression.
60
Matching Through Metacharacters
61
The End
62