0% found this document useful (0 votes)
7 views9 pages

Intro_to_javascript[12290]

The document provides an introduction to JavaScript, comparing static and dynamic web pages, and explaining how to run JavaScript programs either embedded in HTML or through external files. It covers key concepts such as variables, data types, control structures, loops, arrays, operators, and functions, along with best practices for writing code. Additionally, it discusses user interaction through prompt windows and the importance of comments and code organization.

Uploaded by

Richiana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views9 pages

Intro_to_javascript[12290]

The document provides an introduction to JavaScript, comparing static and dynamic web pages, and explaining how to run JavaScript programs either embedded in HTML or through external files. It covers key concepts such as variables, data types, control structures, loops, arrays, operators, and functions, along with best practices for writing code. Additionally, it discusses user interaction through prompt windows and the importance of comments and code organization.

Uploaded by

Richiana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Intro_to_javascript[12290] Page 1 of 9

JAVASCRIPT

Static Web Page vs Dynamic Web Page

Contents & layout Contents & layout CAN be


CANNOT change modified by a built-in program.

Client-side programming vs Server-side program

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.

Tips for writing JavaScript programs


➢ Use comments extensively to document your program and its features.
➢ Use indented code where appropriate to make the code easier to read and follow.
➢ Be careful of uppercase and lowercase letters – JavaScript is CASE sensitive.
➢ Test your code on several browsers if at all possible.
➢ Each line of code ends with a semi-colon “;”.
Intro_to_javascript[12290] Page 2 of 9

Simple output to a Webpage


▪ document.write (“… text …”);
or
document.writeln (“... text …”);
where text = text and/or HTML tags included in the quotes are displayed on the Web page.
write vs writeln: the same except “writeln” attaches a CR (carriage return) to the text.
▪ alert (“…text…”);
The alert () method creates a pop-up window that alerts the user to some special condition.
Syntax: alert (………); OR window.alert (…..);
The text given within the brackets and placed in quotation marks will be displayed in the alert window.
▪ status bar: status= “….text….”;

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

Retrieving Information from the user - The Prompt Window


A prompt window contains a question or a short message, a text field, and 3 clickable buttons (OK, clear and
cancel). The buttons determine how the browser handles the information that currently resides in the text field.
Clear Erases everything that appears in the text field. The value of the text field is set to null. The
Clear button will not close the window.
OK Closes the prompt window and stores the information appearing in the text field to the assigned
variable. Closing the window with an empty text field returns a null value to the variable.
Cancel Cancels the current operation. The window is closed and a null value is returned.
Example:
var fname = prompt (“What is your first name? “);
document.write (“Hello “ + fname);
Intro_to_javascript[12290] Page 4 of 9

JAVASCRIPT CONTROL STRUCTURES

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;
}

MULTIPLE SELECTION - THE SWITCH STATEMENT


The syntax of the switch statement is as follows:
Switch (expression)
{ case label: statement;
[ statement;]
break;
[case label: statement;
[statement;]
break;]
[default: statement;]
}

▪ 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
}

➢ When a for loop executes, the following occurs:


1. The initializing expression initial-expression, if any, is executed. This expression usually initializes one
or more loop counters, but the syntax allows an expression of any degree of complexity.
2. The condition expression is evaluated. If the value of condition is true, the loop statements execute. If
the value of condition is false, the for loop terminates.
3. The update expression increment-expression executes.
4. The statements execute, and control returns to step 2.

➢ 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.

Storing data in an array element


Days[0] = “Sunday”; store “Sunday” in the first element of array “days”

Data Type of an Array


Array elements can be of mixed data types
Eg: var days = [“Monday”, 34, “Wednesday”, 23.56];

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.

JavaScript Functions & Procedures


In JavaScript all ‘procedures’ and ‘functions’ are referred to as functions – that is whether the segment of code
needs to return a value, or not, it is still called a function. (Unlike many other programming languages.)

Function definition
function fnName (. . . parameter list . . .)
{
statement;
.......
statement; body of the function
}
Intro_to_javascript[12290] Page 9 of 9

The Return statement


Functions that need to return a result must use the return statement.
For example:
function Total (a, b)
{
var result = a + b;
return result;
}
To call the above function, two numeric parameters need to be passed, either as literals or variables.
Eg 1: sum = Total (2,3);
Eg 2: sum = Total (n1, n2); assuming n1 and n2 have been given numeric values prior to the statement.

Local and Global variables


➢ Any global variables (variables declared within the main section of the scripting code) may be used within a
function. However, care must be taken that problems aren’t caused since all other sections of code (other
functions, the main section, etc.) may also use, and alter, the same variable.
➢ A local variable may be defined within a function, hence may be used only within that function.
For example:
function doSomeThing ( )
{ var n1 = 5;
.....
} Variable, n1, is declared as a local variable to the function doSomeThing
Different functions can use the same names for local variables.

➢ 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

You might also like