Download Client Side Programming - Introduction to Java Script - Lecture Slides and more Slides Javascript programming in PDF only on Docsity! Client-Side Programming: the JavaScript Language WWW Structures, Techniques and Standards docsity.com JavaScript History and Versions • JavaScript was introduced as part of the Netscape 2.0 browser • Microsoft soon released its own version called JScript • ECMA developed a standard language known as ECMAScript • ECMAScript Edition 3 is widely supported and is what we will call “JavaScript” docsity.com JavaScript Introduction • Web page and alert box generated by JSHelloWorld.html document and JSHelloWorld.js code: docsity.com JavaScript Introduction
* Prompt window example:
var inString = window.prompt("Enter JavaScript code to be tested:",
my;
[JavaScript Application]
Q Enter JavaScript code to be tested:
window, alert(12+-7))
docsity.com
JavaScript Properties • Note that JavaScript code did not need to be compiled • JavaScript is an interpreted language • Portion of browser software that reads and executes JavaScript is an interpreter • Interpreted vs. compiled languages: • Advantage: simplicity • Disadvantage: efficiency docsity.com JavaScript Properties • All data in JavaScript is an object or a property of an object • Types of JavaScript objects • Native: provided by scripting engine • If automatically constructed before program execution, known as a built-in object (ex: window) • Host: provided by host environment • alert and prompt are host objects docsity.com Developing JavaScript Software • Writing JavaScript code • Any text editor (e.g., Notepad, Emacs) • Specialized software (e.g., MS Visual InterDev) • Executing JavaScript • Load into browser (need HTML document) • Browser detects syntax and run-time errors • Mozilla: JavaScript console lists errors • IE6: Exclamation icon and pop-up window docsity.com Developing JavaScript Software • Mozilla JavaScript console (Tools | Web Development | JavaScript Console): docsity.com Developing JavaScript Software • Debugging • Apply generic techniques: desk check, add debug output (alert’s) • Use specialized JavaScript debuggers: later • Re-executing • Overwrite .js file • Reload (Mozilla)/Refresh (IE) HTML document that loads the file docsity.com Basic JavaScript Syntax
// HighLow.js
var thinkingOf; // Number the computer has chosen (1 through 1000)
var guess; // User’s latest guess
// Initialize the computer’s number
thinkingOf = Math.ceil(Math.random()*1000) ;
// Play until user guesses the number
guess = window.prompt("I’m thinking of a number between 1 and 1000." +
“What is it?", "");
docsity.com
Basic JavaScript Syntax Notice that there is no main() function/method docsity.com Basic JavaScript Syntax Semi-colons are usually not required, but always allowed at statement end docsity.com Basic JavaScript Syntax
// HighLow.js
var thinkingOf; // Number the computer has chosen (1 through 1000)
var guess; // User’s latest guess
// Initialize the computer’s number
thinkingOf \6 Math.ceil (Math. random(
000);
// Play until user guesses
guess window. prompt ("I’m thinking of a number between 1 and 1000." +
“What is it?", "");
Arithmetic operators same as Java/C++
(® docsity.com
Basic JavaScript Syntax String concatenation operator as well as addition docsity.com Basic JavaScript Syntax
while (guess != thinkingOf)
{
// Evaluate the user’s guess
if (guess < thinkingOf) {
guess = window.prompt ("Your guess of " + guess +
"was too low. Guess again.", "");
}
else {
guess = window.prompt ("Your guess of "+ guess +
"was too high. Guess again.", "");
}
}
// Game over; congratulate the user
window.alert(guess + " is correct!");
(® docsity.com
Basic JavaScript Syntax Many control constructs and use of { } identical to Java/C++ docsity.com Basic JavaScript Syntax Most relational operators syntactically same as Java/C++ docsity.com Variables and Data Types • typeof operator returns string related to data type • Syntax: typeof expression • Example: docsity.com Variables and Data Types
TABLE 4.1: Values returned by typeof for various operands.
Operand Value String typeof Returns
null "object"
Boolean "boolean"
Number "number"
String "string"
native Object representing fimetion "function"
native Object not representing fumction | "object"
declared variable with no value "undefined"
undeclared variable "undefined"
nonexistent property of an Object "undefined"
® docsity.com
Variables and Data Types • Common automatic type conversions: • Compare String and Number: String value converted to Number • Condition of if or while converted to Boolean • Array accessor (e.g., 3 in records[3]) converted to String docsity.com Variables and Data Types Special Number values (“Not a Number” and number too large to represent) docsity.com Variables and Data Types
TABLE 4.4: Data type conversions to Number.
Original Value Value as Number
undefined Nall
null, false, "" (empty string) | 0
true 1
String representing number represented number
other String Nall
Object call to valueOf() method on the object
® docsity.com
Variables and Data Types • Syntax rules for names (identifiers): • Must begin with letter or underscore ( _ ) • Must contain only letters, underscores, and digits (or certain other characters) • Must not be a reserved word docsity.com JavaScript Statements • Expression statement: any statement that consists entirely of an expression • Expression: code that represents a value • Block statement: one or more statements enclosed in { } braces • Keyword statement: statement beginning with a keyword, e.g., var or if docsity.com JavaScript Statements • var syntax: • Java-like keyword statements: Comma-separated declaration list with optional initializers docsity.com JavaScript Statements JavaScript keyword statements are very similar to Java with small exceptions docsity.com JavaScript Statements
// Can use ‘var’ to define a loop variable inside a ‘for’
for (var i=1; i<=3; i++) {
switch (i) {
// ?case’ value can be any expression and data type,
/f not just constant int as in Java. Automatic
// type conversion is performed if needed.
case 1.0 + 2:
window.alert("i = "+ i);
break;
default:
try {
throw("A JavaScript exception can be anything");
window.alert ("This is not executed.");
}
{/ Do not supply €@Gepeien GatayEyBD in catch’
catch @ f{
window.alert("Caught: " + 2);
}
break;
>
docsity.com
JavaScript Operators • Operators are used to create compound expressions from simpler expressions • Operators can be classified according to the number of operands involved: • Unary: one operand (e.g., typeof i) • Prefix or postfix (e.g., ++i or i++ ) • Binary: two operands (e.g., x + y) • Ternary: three operands (conditional operator) docsity.com JavaScript Operators
TABLE 4.6: Precedence (high to low) for selected JavaScript operators.
Operator Category Operators
Object Creation new
Postfix Unary t+, —-
Prefix Unary delete, typeof, ++,-- ,+,-,7,!
Multiplicative a fh
Additive +,-
Shift <<, >>, >>>
Relational <, >, <=, >=
(Un jequality ss, I=, ===, l==
Bitwise AND &
Bitwise XOR *
Bitwise OR |
Li weical AND hk
Le ical OR l|
Conditional and Assignment | 7:, =, *=, /=, #=, t=, -=, <<=, >>=, >>>=,
i=, “=, |=
docsity.com
JavaScript Operators: Automatic Type Conversion • Operators ==, != convert both operands to Number • Exception: If both operands are String, no conversion is performed (lex. comparison) • Exception: values of Undefined and Null are equal(!) • Exception: instance of Date built-in “class” is converted to String (and host object conversion is implementation dependent) • Exception: two Objects are equal only if they are references to the same object docsity.com JavaScript Operators: Automatic Type Conversion • Operators ===, !== are strict: • Two operands are === only if they are of the same type and have the same value • “Same value” for objects means that the operands are references to the same object • Unary +, - convert their operand to Number • Logical &&, ||, ! convert their operands to Boolean docsity.com JavaScript Numbers • Syntactic representations of Number • Integer (42) and decimal (42.0) • Scientific notation (-12.4e12) • Hexadecimal (0xfa0) • Internal representation • Approximately 16 digits of precision • Approximate range of magnitudes • Smallest: 10-323 • Largest: 10308 (Infinity if literal is larger) docsity.com JavaScript Functions • Function declaration syntax Declaration always begins with keyword function, no return type docsity.com JavaScript Functions • Function declaration syntax Identifier representing function’s name docsity.com JavaScript Functions
* Function declaration syntax
Formal parameter list
function oneTo@igh) {
return Math.ceil(Math.random()*high) ;
}
® docsity.com
JavaScript Functions • Function call syntax Function call is an expression, can be used on right-hand side of assignments, as expression statement, etc. docsity.com JavaScript Functions
¢ Function call syntax
thinkingOf = @iglex1000) ;
Function name
docsity.com
JavaScript Functions
¢ Function call syntax
thinkingOf = oneTo@O0D);
Argument list
docsity.com
JavaScript Functions • Function call semantics: Expression(s) in body evaluated as if formal parameters are variables initialized by argument values docsity.com JavaScript Functions • Function call semantics: If final statement executed is return-value, then value of its expression becomes value of the function call docsity.com JavaScript Functions • Function call semantics: Value of function call is then used in larger expression containing function call. docsity.com JavaScript Functions • Local vs. global variables Global variable: declared outside any function docsity.com JavaScript Functions • Local vs. global variables Local variable declared within a function docsity.com JavaScript Functions • Local vs. global variables Local declaration shadows corresponding global declaration Output is 6 docsity.com JavaScript Functions • Explicit type conversion supplied by built-in functions • Boolean(), String(), Number() • Each takes a single argument, returns value representing argument converted according to type-conversion rules given earlier docsity.com Object Introduction • An object is a set of properties • A property consists of a unique (within an object) name with an associated value • The type of a property depends on the type of its value and can vary dynamically prop is Boolean prop is now String prop is now Number docsity.com Object Introduction • There are no classes in JavaScript • Instead, properties can be created and deleted dynamically Create an object o1 Create property testing Delete testing property docsity.com Property Creation • Assignment to a non-existent (even if inherited) property name creates the property: • Object initializer notation can be used to create an object (using Object() constructor) and one or more properties in a single statement: docsity.com Enumerating Properties • Special form of for statement used to iterate through all properties of an object: Produces three alert boxes; order of names is implementation-dependent. docsity.com Accessing Property Values • The JavaScript object dot notation is actually shorthand for a more general associative array notation in which Strings are array indices: • Expressions can supply property names: Converted to String if necessary docsity.com Object Values • Value of Object is reference to object: o1 is changed docsity.com Object Values • Value of Object is reference to object: Output is Hello World! docsity.com Object Values
* Object argument values are references
// Create two different objects with identical data
var o1 = new Object();
ol.data = "original";
var o2 = new Object();
o2.data = "original";
// Call the function on these objects and display the results
objaArgs(ol, o2);
function objArgs(parami, param2) {._.}
® docsity.com
Object Values
* Object argument values are references
function objArgs(param1, param?) {
// Change the data in parami and its argument
parani.data = "changed";
param 1
Gera = peat) referenced by param2, but not its argument
data data
changed original
I I
ol 02
docsity.com
Object Values
* Object argument values are references
param 1 param2
|
data data
changed original
I I
ol 02
[JavaScript Application]
ANY param is changed
param? is changed
[JavaScript Application]
AN ol is changed
o2 is original
docsity.com
Object Methods • JavaScript functions are stored as values of type Object • A function declaration creates a function value and stores it in a variable (property of window) having the same name as the function • A method is an object property for which the value is a function docsity.com Object Methods Creates isLeaf() method that is defined by leaf() function docsity.com Object Methods Refers to object that “owns” method when leaf() is called as a method docsity.com Object Methods
var nodel makeBTNode (3);
var node? = makeBTNode(7);
nodel.right = node2;
// Output the value of isLeaf() on each node
wWindow.alert("nodei is a leaf: " + nodei.isLeaf());
window.alert ("node2 is a leaf: " + node2.isLeaf());
docsity.com