Intro_to_javascript[12290]
Intro_to_javascript[12290]
JAVASCRIPT
Program scripts are run from browser Scripts are stored and executed
on client’s computer. (eg: JavaScript /Jscript) on server
Running JavaScript
Two ways to create a JavaScript program:
1. Place the JavaScript commands directly into the HTML document.
2. Place the JavaScript commands in an external file. Thus hides the JavaScript code from the user. However, this
causes the Web Server to have to transfer 2 files on request.
<Script> tag
➢ A two-sided tag which identifies the beginning and end of a client-side program.
➢ The <script> tag when there is a separate file with the scripting code:
<script src = “url” language = “language”>
……… script commands and comments ….
</script>
Where url = filename of an external document containing the program code;
language = what language is the code. E.g.: JavaScript
➢ When placing the scripting code within the HTML document:
Place <script> tag in <head> section or <body> section. It is highly recommended to place it within the
<head> section so as to keep separate the code from the contents and layout. However, there are instances
when this is not possible.
VARIABLES
Variable names:
▪ Names must begin with a letter, digit or the underscore (_).
▪ One cannot use spaces
▪ Recall everything in JavaScript is case sensitive, therefore fname; FNAME and FnaMe are all different
variables.
▪ No reserved words are allowed to be used.
Data Types
▪ Numeric integers or real
▪ Strings place in quotes to indicate string value
▪ Boolean true or false
▪ null null value means “no value as yet” – not nil or zero
Creating / declaring variables
▪ No need to state the data type, just use the keyword var.
For example: var first = 23;
var second = “some words”;
var third = second;
var first_Boolean = true;
var VistorName;
▪ To use a variable in the “write” method, one must use a “+” symbol (to concatenate to the other strings).
For example: document.write (“The number is “ + first);
var second = “some words”;
document.write (“<h2>” + second + “</h2>”);
Intro_to_javascript[12290] Page 3 of 9
BINARY SELECTION
if (condition)
{ statements if condition true;
}
else
{ statements if condition false;
}
A nested if...else can also be achieved as follows – just remember the brackets…
if (condition1)
{ if (condition2)
{ Statements if condition1 and condtion2 are true;
}
else
{ statements if condition1 is true and condition2 is false;
}
}
else
{ statements if condition1 and condition2 are false;
}
▪ A switch selects between a number of choices depending upon the value of the expression.
▪ The choices identified by case statements, each has a label which equals one of the potential values of the
expression.
▪ If none of the cases matches the expression, the optional default may be used instead.
▪ Each case includes one or more statements and is terminated by a break. If you omit the break you’ll get
random, potentially harmful, behavior.
Intro_to_javascript[12290] Page 5 of 9
REPETITION
For Statement
for ([initial-expression]; [condition]; [increment-expression])
{ statements
}
➢ The For statement contains 3 statements, separated by semicolons, within parenthesis. The 1st statement
initializes the counter, the 2nd tells the program when the loop has finished and the 3rd statement contains
an operation that is performed to the counter at the end of each loop.
Example:
for (var count = 0; count < 12; count++)
{ // repeated statements go here
document.write (“<p> The counter is “ + count);
document.write (“</p>);
}
While Statement
A while statement repeats a loop as long as a specified condition evaluates to true. A while statement looks as
follows:
while (condition)
{ statements
}
➢ If the condition becomes false, the statements within the loop stop executing and control passes to the
statement following the loop.
➢ The condition test occurs only when the statements in the loop have been executed and the loop is about to
be repeated. That is, the condition test is not continuous but is performed once at the beginning of the loop
and again just following the last statement in statements, each time control passes through the loop.
Example: The following while loop iterates as long as n is less than three:
n = 0;
x = 0;
while ( n < 3 )
{ n ++;
x += n;
}
Intro_to_javascript[12290] Page 6 of 9
Other Statements
Break
The break statement terminates the current while or for loop and transfers program control to the statement
following the terminated loop. Use break with care. A break statement looks as follows: break;
Example: The following code segment has a break statement that terminates the while loop when i is three, and
then displays the value i
var i = 0
while (i < 6) {
if (i == 3)
break;
i++
}
document.write (i)
Continue Statement
A continue statement terminates execution of the block of statements in a while or for loop and continues
execution of the loop with the next iteration. A continue statement looks as follows: continue;
In contrast to the break statement, continue does not terminate the execution of the loop entirely. Instead,
➢ In a while loop, it jumps back to the condition.
➢ In a for loop, it jumps to the increment-expression.
Example.
The following example shows a while loop with a continue statement that executes when the value of i is
three. Thus, n takes on the values one, three, seven, and twelve.
i = 0;
n = 0;
while (i < 5)
{ i++;
if (i == 3)
continue;
n += I;
}
JAVASCRIPT ARRAYS
Create an Array
var days = [“Monday”, “Tuesday”, “Wednesday”, “Thursday”];
or
var days = new Array (“Monday”, “Tuesday”, “Wednesday”, “Thursday”);
or
var days = new Array (4);
Note:
1. The first declaration has square brackets.
2. The second declaration – declaring the array using the object declaration format – has round brackets.
3. The third declaration does not initialize the contents of the array to anything, just creates the array.
Intro_to_javascript[12290] Page 7 of 9
Array Subscripts
➢ Use square brackets
➢ Always starts at zero.
Size of an array
Var data = [“Monday”, “Tuesday”, 34, 76.45, “Wednesday”]; …. Creates an array of 5 elements
data [5] = “Thursday”; …. array extended and new element added
data [23] = 48; …. array expanded so that it is long enough;
places 48 into position 23.
The array elements 6 – 22 will be undefined.
Accessing an array element
➢ Use the subscript notation
- eg: data[2]
- or data[count]
➢ When displaying the contents of an array – how many elements does the array have? Use the length attribute.
Eg: var len = data.length;
Intro_to_javascript[12290] Page 8 of 9
JavaScript Operators
Operator Description
+ Arguments numbers: arguments added together and result returned.
Arguments strings: arguments concatenated and result returned.
- If supplied with two operands this subtracts one from the other. If supplied with a single operand it
reverses the sign.
* Multiplies two numbers together.
/ Divides the first number by the second.
% Modulus division returns the integer remainder from a division.
! Logical NOT returns false if the operand evaluates to true. Otherwise returns true.
== Returns true if the operands are equal.
!= Returns true if the operands are not equal.
> Returns true if left operand is greater than right operand.
>= Returns true if left operand is greater than or equal to right operand.
< Returns true if left operand is less than right operand.
<= Returns true if left operand is less than or equal to right operand.
&& Logical AND returns true if both operands are true. Otherwise returns false.
|| Logical OR returns true if one or both operands are true, otherwise returns false.
= Assigns a value to a variable.
+= Adds two numbers then assigns the result to the one on the left of the expression.
-+ Subtracts the term on the right from the term on the left, then assigns the result to the one on the left
of the expression.
*= Multiplies two values then assigns the result to the one on the left of the expression.
/= Divides the terms on the left by the term on the right and then assigns the result to the one on the left
of the expression.
%= Performs modulus division then assigns the result to the one on the left of the expression.
++ Auto-increment, increases the value of its (integer) argument by one.
-- Auto-decrement, decreases the value of an integer by one.
Function definition
function fnName (. . . parameter list . . .)
{
statement;
.......
statement; body of the function
}
Intro_to_javascript[12290] Page 9 of 9
➢ When values are passed as parameters (more efficient than using global variables), one needs to be careful
how the variable is passed – by Value, by Reference or by Constant Reference. In many languages it’s the
programmer’s decision as to which method will be used to pass the parameter, however within JavaScript
the method of passing depends on the data type of the parameter.
Parameter Data Type Method used
Numeric By Value
Boolean By Value
Objects By Reference
Arrays By Reference
Strings By Constant Reference
Functions By Constant Reference