0% found this document useful (0 votes)
38 views

Internet Programming - 03

The document discusses various JavaScript programming concepts including: 1) Algorithms, program control, pseudocode, and flowcharts for developing programs. 2) Client-side scripting advantages like modifying pages without reloading. 3) Conditional structures like if/else statements and switch statements for program flow. 4) Looping structures like while, for, and do/while loops for repetition. 5) Functions for modularizing code and passing parameters/arguments. 6) Arrays for storing multiple values in a single variable.

Uploaded by

mmmm
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Internet Programming - 03

The document discusses various JavaScript programming concepts including: 1) Algorithms, program control, pseudocode, and flowcharts for developing programs. 2) Client-side scripting advantages like modifying pages without reloading. 3) Conditional structures like if/else statements and switch statements for program flow. 4) Looping structures like while, for, and do/while loops for repetition. 5) Functions for modularizing code and passing parameters/arguments. 6) Arrays for storing multiple values in a single variable.

Uploaded by

mmmm
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

Internet Programming

Javascript
Introduction
▪ Algorithm is a procedure for solving a problem in terms of
▪ the actions to be executed
▪ the order in which the actions are to be executed
▪ Program Control is specifying the execution order of the statements in a computer program.
▪ Pseudocode is an artificial and informal language that helps programmers develop algorithms.

▪ Flowchart is a graphical representation of an algorithm.

2
Client Side Script
▪ Client-side script: code runs in browser after page is sent back from server, often this code
manipulates the page or responds to user actions.
▪ JavaScript Advantages:
▪ Usability: can modify a page without having to post back to the server (faster UI).
▪ Efficiency: can make small, quick changes to page without waiting for server.
▪ Event-driven: can respond to user actions like clicks and key presses.

3
Structure Types
▪ A selection structure is used to choose among alternative courses of action in a program.
▪ A repetition structure (also known as a loop) allows the programmer to specify that a script is
to repeat an action while some condition remains true.

4
If statement
• if ( condition)
statement;

5
If statement (cont.)
• if ( studentGrade >= 60 )
document.writeln( "Passed" );

6
If-else statement

7
If-else statement (cont.)
• if ( studentGrade >= 60 )
document.writeln( "Passed" );

• else
document.writeln( "Failed" );

▪ The conditional operator (?:)


document.writeln( studentGrade >= 60 ? "Passed" : "Failed" );

8
If-else statement (cont.)
• if ( grade >= 60 )
• document.writeln( "Passed" );
• else
•{
• document.writeln( "Failed<br />" );
• document.writeln( "You must take this course again." );
•}

9
Nested If-else statement
• if ( studentGrade >= 90 )
document.writeln( "A" );
• else if ( studentGrade >= 80 )
• document.writeln( "B" );
• else if ( studentGrade >= 70 )
• document.writeln( "C" );
• else if ( studentGrade >= 60 )
• document.writeln( "D" );
• else
• document.writeln( "F" );

10
while Repetition Statement
• While(condition)
statement;

11
while Repetition Statement
• var product = 2;
• while ( product <= 1000 )
product = 2 * product;

12
13
14
15
Arithmetic Assignment Operators

16
Increment & Decrement Operators

17
Logical Operators
▪ JavaScript provides logical operators that can be used to form more complex conditions by
combining simple conditions.
▪ The logical operators are
▪ && (logical AND)
▪ || (logical OR)
▪ ! (logical Not also called logical negation)

18
for Repetition Statement
• The general format of the for statement is
• for ( initialization; loopContinuationTest; increment )
statements

19
for Repetition Statement (cont.)

20
for Repetition Statement (cont.)

21
for Repetition Statement (cont.)

22
switch Multiple-Selection Statement

23
switch Multiple-Selection Statement (cont.)
• switch(expression)
•{
case x:
// code block
break;

case y:
// code block
break;

default:
// code block
•}

24
switch Multiple-Selection Statement (cont.)
▪ The switch expression is evaluated once and the expression value is compared with the values
of each case.
▪ When the expression value matches a case value, the associated block of code is executed.
▪ The default code block is executed, if the expression value doesn’t match any case value.

25
26
27
do…while Repetition Statement
• do
•{
• statement
• } while ( condition );

28
29
Break and Continue Statements
▪ The break and continue statements alter the flow of control.
▪ The break statement causes immediate exit from the statement. Execution continues with the
first statement after the structure.
▪ The break statement is commonly used to escape early from a loop or to skip the remainder of
a switch statement.

30
31
32
Labeled Break and Continue Statements
▪ The break statement can break out of an immediately enclosing while, for, do…while or switch
statement.
▪ To break out of a nested set of structures, you can use the labeled break statement.
▪ This statement, when executed in a while, for, do…while or switch statement, causes immediate
exit from that statement and any number of enclosing repetition statements; program
execution resumes with the first statement after the enclosing labeled statement (a statement
preceded by a label).
▪ The labeled statement can be a block (a set of statements enclosed in curly braces, {}).
▪ Labeled break statements commonly are used to terminate nested looping structures
containing while, for, do…while or switch statements.

33
34
35
Functions
▪ Modules in JavaScript are called functions
▪ The prepackaged functions that belong to JavaScript objects (such as Math.pow and
Math.round, introduced previously) are called methods.
▪ Function is invoked (i.e., made to perform its designated task) by a function call.
▪ The function call specifies the function name and provides information (as arguments) that the
called function needs to perform its task.

36
Functions (cont.)
▪ The format of a function definition is
function function-name( parameter-list )
{
declarations and statements
}

37
38
Scope Rules
▪ The scope of an identifier for a variable or function is the portion of the program in which the
identifier can be referenced.
▪ Global variables or script-level variables that are declared in the head element are accessible in any
part of a script and are said to have global scope. Thus every function in the script can potentially
use the variables.
▪ Identifiers declared inside a function have function (or local) scope and can be used only in that
function.
▪ Function scope begins with the opening left brace ({) of the function in which the identifier is
declared and ends at the terminating right brace (}) of the function.
▪ Local variables of a function and function parameters have function scope.
▪ If a local variable in a function has the same name as a global variable, the global variable is “hidden”
from the body of the function.

39
Arrays
▪ An array is a group of memory locations that all have the same name and normally are of the
same type (although this attribute is not required in JavaScript)
▪ Any one of array elements may be referred to by giving the name of the array followed by the
position number of the element in square brackets ([]).
▪ The first element in every array is the zeroth element.
▪ The position number of the element called subscript or index.

40
Arrays Declaration
▪ var c = new Array( 12 );
▪ Empty Array declaration
▪ var c = new Array( );

▪ Array can be initialized during decalaration if the elements are known in advance.
▪ var n = new Array( 10, 20, 30, 40, 50 );
▪ var n = [ 10, 20, 30, 40, 50 ];

41
42
Passing Arrays to Functions
▪ In Java-Script, numbers, boolean values and strings are passed to functions by value.
▪ Arrays and all objects in Java-Script are passed to functions by reference.
▪ The name of an array actually is a reference to an object that contains the array elements and
the length variable, which indicates the number of elements in the array.
▪ var hourlyTemperatures = new Array( 24 );
modifyArray( hourlyTemperatures );

43
Sorting Arrays
▪ The Array object in JavaScript has a built-in method sort for sorting arrays
▪ By default, Array method sort (with no arguments) uses string comparisons to determine the
sorting order of the Array elements. The strings are compared by the ASCII values of their
characters.
▪ Method sort takes an optional argument that is the name of a function (called the comparator
▪ function) that compares its two arguments and returns one of the following:
▪ A negative value if the first argument is less than the second argument
▪ Zero if the arguments are equal
▪ A positive value if the first argument is greater than the second argument

44
Sorting Arrays (cont.)
▪ var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ];
▪ a.sort( compareIntegers ); // sort the array
• function compareIntegers( value1, value2 )
•{
return parseInt( value1 ) - parseInt( value2 );

•}

45
Searching Array
▪ Linear Search

46
Multidimensional Arrays
▪ JavaScript does not support multidimensional arrays directly, but does allow the programmer to
specify arrays whose elements are also arrays.

47
Multidimensional Arrays (cont.)
▪ 2-by-2 array
▪ var b = [ [ 1, 2 ], [ 3, 4 ] ];

▪ 2D Arrays with Rows of Different Lengths


▪ var b = [ [ 1, 2 ], [ 3, 4, 5 ] ];

▪ Creating Two-Dimensional Arrays with new


var b;
b = new Array( 2 ); // allocate rows
b[ 0 ] = new Array( 5 ); // allocate columns for row 0
b[ 1 ] = new Array( 3 ); // allocate columns for row 1

48
Objects
▪ The objects are a natural way of thinking about the world and about scripts that manipulate
HTML documents.
▪ JavaScript uses objects to perform many tasks and therefore is referred to as an object-based
programming language.
▪ All objects have attributes (e.g., size, shape, color and weight), and they all exhibit behaviors
(e.g., a ball rolls, bounces, inflates and deflates; a baby cries, sleeps, crawls, walks and blinks; a
car accelerates, brakes and turns; a towel absorbs water)
▪ Object-oriented design (OOD) models software in terms similar to those that people use to
describe real-world objects.

49
Objects (cont.)
▪ OOD takes advantage of inheritance relationships
▪ new classes of objects are derived by absorbing characteristics of existing classes and adding unique
characteristics of their own.

▪ OOD encapsulates (i.e., wraps) attributes and operations (behaviors) into objects— an object’s
attributes and operations are intimately tied together.

50
Math Object
▪ The Math object’s methods allow you to perform many common mathematical calculations.

51
52
Math Object (cont.)

53
String Object
▪ The String object encapsulates the attributes and behaviors of a string of characters.

Method Description
charAt( index ) Returns a string containing the character at the specified index. If
there is no character at the index, charAt returns an empty string.
The first character is located at index 0.
charCodeAt( index ) Returns the Unicode value of the character at the specified index,
or NaN (not a number) if there is no character at that index.
concat( string ) Concatenates its argument to the end of the string that invokes the
method. The string invoking this method is not modified; instead
a new String is returned. This method is the same as adding two
strings with the string-concatenation operator + (e.g., s1.concat(
s2) is the same as s1 + s2).

54
Method Description
fromCharCode( value1, value2, …) Converts a list of Unicode values into a string containing the corresponding
characters.
indexOf( substring, index ) Searches for the first occurrence of substring starting from position index in
the string that invokes the method. The method returns the starting index of
substring in the source string or –1 if substring is not found. If the index
argument is not provided, the method begins searching from index 0 in the
source string.
lastIndexOf( substring, index ) Searches for the last occurrence of substring starting from position index and
searching toward the beginning of the string that invokes the method. The
method returns the starting index of substring in the source string or –1 if
substring is not found. If the index argument is not provided, the method
begins searching from the end of the source string.
replace( searchString, replaceString ) Searches for the substring searchString, and replaces the first occurrence
with replaceString and returns the modified string, or the original string if no
replacement was made.
slice( start, end ) Returns a string containing the portion of the string from index start through
index end. If the end index is not specified, the method returns a string from
the start index to the end of the source string. A negative end index specifies
an offset from the end of the string, starting from a position one past the end
of the last character (so –1 indicates the last character position in the string).
55
Method Description
split( string ) Splits the source string into an array of strings (tokens), where its string
argument specifies the delimiter (i.e., the characters that indicate the end of
each token in the source string).
substr( start, length ) Returns a string containing length characters starting from index start in the
source string. If length is not specified, a string containing characters from
start to the end of the source string is returned.
substring( start, end ) Returns a string containing the characters from index start up to but not
including index end in the source string.
toLowerCase() Returns a string in which all uppercase letters are converted to lowercase
letters. Nonletter characters are not changed.
toUpperCase() Returns a string in which all lowercase letters are converted to uppercase
letters. Nonletter characters are not changed.

56
String Object (cont.)
▪ Methods that generate HTML tags
Method Description
anchor( name ) Wraps the source string in an anchor element (<a></a>) with name as the
anchor name.
fixed() Wraps the source string in a <tt></tt> element (same as <pre></pre>).
link( url ) Wraps the source string in an anchor element (<a></a>) with url as the
hyperlink location.
strike() Wraps the source string in a <strike></strike> element.
sub() Wraps the source string in a <sub></sub> element.

sup() Wraps the source string in a <sup></sup> element.

57
Date Object
▪ JavaScript’s Date object provides methods for date and time manipulations.
▪ Date and time processing can be performed based on the computer’s local time zone or based
on World Time Standard’s Coordinated Universal Time (abbreviated UTC)—formerly called
Greenwich Mean Time (GMT).

Method Description
getDate() Returns a number from 1 to 31 representing the day of the month in local
getUTCDate() time or UTC.
getDay() Returns a number from 0 (Sunday) to 6 (Saturday) representing the day of the
getUTCDay() week in local time or UTC.
getFullYear() Returns the year as a four-digit number in local time or UTC.
getUTCFullYear()
getHours() Returns a number from 0 to 23 representing hours since midnight in local time
getUTCHours() or UTC.

58
Method Description
getMilliseconds() Returns a number from 0 to 999 representing the number of milliseconds in
getUTCMilliSeconds() local time or UTC, respectively. The time is stored in hours, minutes, seconds
and milliseconds.
getMinutes() Returns a number from 0 to 59 representing the minutes for the time in local
getUTCMinutes() time or UTC.
getMonth() Returns a number from 0 (January) to 11 (December) representing the month
getUTCMonth() in local time or UTC.
getSeconds() Returns a number from 0 to 59 representing the seconds for the time in local
getUTCSeconds() time or UTC.
getTime() Returns the number of milliseconds between January 1, 1970, and the time in
the Date object.
getTimezoneOffset() Returns the difference in minutes between the current time on the local
computer and UTC (Coordinated Universal Time).
setDate( val ) Sets the day of the month (1 to 31) in local time or UTC.
setUTCDate( val )
setFullYear( y, m, d ) Sets the year in local time or UTC. The second and third arguments
setUTCFullYear( y, m, d ) representing the month and the date are optional. If an optional argument is
not specified, the current value in the Date object is used.

59
Method Description
setHours( h, m, s, ms ) Sets the hour in local time or UTC. The second, third and fourth arguments, representing
setUTCHours( h, m, s, ms ) the minutes, seconds and milliseconds, are optional. If an optional argument is not
specified, the current value in the Date object is used.
setMilliSeconds( ms ) Sets the number of milliseconds in local time or UTC.
setUTCMilliseconds( ms )
setMinutes( m, s, ms ) Sets the minute in local time or UTC. The second and third arguments, representing the
setUTCMinutes( m, s, ms ) seconds and milliseconds, are optional. If an optional argument is not specified, the
current value in the Date object is used.
setMonth( m, d ) Sets the month in local time or UTC. The second argument, representing the date, is
setUTCMonth( m, d ) optional. If the optional argument is not specified, the current date value in the Date
object is used.
setSeconds( s, ms ) Sets the second in local time or UTC. The second argument, representing the milliseconds,
setUTCSeconds( s, ms ) is optional. If this argument is not specified, the current millisecond value in the Date
object is used.
setTime( ms ) Sets the time based on its argument—the number of elapsed milliseconds since January 1,
1970.
toLocaleString() Returns a string representation of the date and time in a form specific to the computer’s
locale. For example, September 13, 2007, at 3:42:22 PM is represented as 09/13/07
15:47:22 in the United States and 13/09/07 15:47:22 in Europe.
60
Method Description
toUTCString() Returns a string representation of the date and time in the form: 15 Sep 2007 15:47:22
UTC
toString() Returns a string representation of the date and time in a form specific to the locale of the
computer (Mon Sep 17 15:47:22 EDT 2007 in the United States).
valueOf() The time in number of milliseconds since midnight, January 1, 1970. (Same as getTime.)

61
Boolean and Number Objects
▪ JavaScript provides the Boolean and Number objects as object wrappers for boolean true/ false
values and numbers, respectively.
▪ These wrappers define methods and properties useful in manipulating boolean values and
numbers. Wrappers provide added functionality for working with simple data types

62
Boolean Object
▪ var b = new Boolean( booleanValue );
▪ The constructor argument booleanValue specifies whether the value of the Boolean object
should be true or false.
▪ If booleanValue is false, 0, null, Number.NaN or an empty string (""), or if no argument is
supplied, the new Boolean object contains false. Otherwise, the new Boolean object contains
true.

Method Description
toString() Returns the string "true" if the value of the Boolean object is true;
otherwise, returns the string "false".

valueOf() Returns the value true if the Boolean object is true; otherwise, returns false.

63
Number Object
▪ var n = new Number( numericValue );

Method Description
toString( radix ) Returns the string representation of the number. The optional radix
argument (a number from 2 to 36) specifies the number’s base.
For example, radix 2 results in the binary representation of the number, 8
results in the octal representation, 10 results in the decimal representation
and 16 results in the hexadecimal representation.
valueOf() Returns the numeric value.

64
Number Object (cont.)
Property Description
Number.MAX_VALUE This property represents the largest value that can be stored in a JavaScript
program - approximately 1.79E+308.
Number.MIN_VALUE This property represents the smallest value that can be stored in a JavaScript
program—approximately 5.00E–324.
Number.NaN This property represents not a number—a value returned from an arithmetic
expression that does not result in a number (e.g., the expression parseInt(
"hello" ) cannot convert the string "hello“ into a number, so parseInt would
return Number.NaN.
To determine whether a value is NaN, test the result with function isNaN,
which returns true if the value is NaN; otherwise, it returns false.
Number.NEGATIVE_INFINITY This property represents a value less than -Number.MAX_VALUE.
Number.POSITIVE_INFINITY This property represents a value greater than Number.MAX_VALUE.

65
document Object
• The Document Object Model (DOM) gives you access to all the elements on a web page. Using
JavaScript, you can dynamically create, modify and remove elements in the page.

Method or property Description


getElementById( id ) Returns the DOM node representing the HTML element whose id attribute
matches id.
write( string ) Writes the string to the HTML document as HTML code.
writeln( string ) Writes the string to the HTML document as HTML code and adds a newline
character at the end.
cookie A string containing the values of all the cookies stored on the user’s
computer for the current document.
lastModified The date and time that this document was last modified.

66
window object
• The window object provides methods for manipulating
browser windows.
Method Description
open(url, name, options ) Creates a new window with the URL of the window set to url, the name set
to name to refer to it in the script, and the visible features set by the string
passed in as option.
prompt(prompt, default ) Displays a dialog box asking the user for input. The text of the dialog is
prompt, and the default value is set to default.
close() Closes the current window and deletes its object from memory.
focus() This method gives focus to the window (i.e., puts the window in the
foreground, on top of any other open browser windows).
blur() This method takes focus away from the window (i.e., puts the window in the
background).
67
window Object (cont.)
Property Description
window.document This property contains the document object representing the document
currently inside the window.
window.closed This property contains a boolean value that is set to true if the window is
closed, and false if it is not.
window.opener This property contains the window object of the window that opened the
current window, if such a window exists.

68
69
70
71
72
73
74
75
76
77
78
79
80
81
Event Propagation
• The standard DOM Events describes 3 phases of event propagation:
• Capturing phase – the event goes down to the element.
• Target phase – the event reached the target element.
• Bubbling phase – the event bubbles up from the element.

82
83
Event Bubbling
• Event bubbling is the process whereby events fired in child elements “bubble” up to their
parent elements. When an event is fired on an element, it’s first delivered to the element’s
event handler (if any), then to the parent element’s event handler (if any).
• If you intend to handle an event in a child element alone, you should cancel the bubbling of
the event in the child element’s event-handling code by using the cancelBubble property of the
event object.

84
85
addEventListener
• addEventListener(event, function, useCapture)
• event : The event name.
◦ Do not use the "on" prefix. Use "click" instead of "onclick".

• function : The function to run when the event occurs.


• useCapture : (Optional , default = false)
◦ true - The handler is executed in the capturing phase.
◦ false - The handler is executed in the bubbling phase.

86
Load Event
• The load event fires when the window finishes loading successfully (i.e., all its children are
loaded and all external files referenced by the page are loaded).
• Actually, every DOM element has a load event, but it’s most commonly used on the window
object

87
88
Thank You
References
▪ Deitel, Harvey M., Paul J. Deitel, and Tem R. Nieto. Internet & world wide web: how to
program.
▪ https://www.w3schools.com/jsref/dom_obj_event.asp
▪ https://javascript.info/event-delegation
▪ https://www.w3schools.com/cssref/css_selectors.php

90

You might also like