Upload
julie-iskander
View
217
Download
1
Embed Size (px)
Citation preview
Intake 33 -‐ OS Julie Iskander 2012-‐2013
1
Client-‐Side JavaScript Lecture 1
Introduction to JavaScript It is a
Lightweight scripting language Interpreted at runtime by JavaScript engines
It is ai
Dynamic scripting language, Has flexible data-‐type Functions are objects.
iiFrom Brendan Eich, JavaScript Creator, Interview “Making web pages come alive “ Netscape needed a scripting language or some kind of language inside the browser that could be used to automate parts of a web page or make a web page more dynamic. The new language should look like Java, but be a scripting language. LiveScript was the official name it was given when it first shipped in beta releases of Netscape Navigator 2.0 in September 1995, but was renamed to JavaScript in a joint announcement with Sun on December 4, 1995. Difference between Java and JavaScript can be summarized to:
Java JavaScript Strongly-‐typed Loosely-‐typed Static Dynamic Classical Prototypal Classes Functions Constructors Functions Methods Functions
Intake 33 -‐ OS Julie Iskander 2012-‐2013
2
i Standardizing JavaScript started right after Navigator 3.0 was released, in August 1996. A draft standard based on JavaScript was submitted to the European Computer Manufacturers' Association (ECMA), the international communications standards body, based in Geneva, Switzerland. ECMA adopted it in June 1997, and it has also just been approved as an ISOstandard. The standard is now officially called ECMAScript. The HTML part, the Document Object Model (DOM), is standardized by the W3C. HTML is read and processed by the web browser. When the browser reads JavaScript code within your HTML document, it processes the code, then displays any output within the web page. The computer reading the JavaScript must have a JavaScript interpreter, a program that interprets the script and runs it, and that interpreter must be enabled.
If there are any errors in the code written in a compiled language, those errors will pop up when the code is compiled. In the case of an interpreted language, errors won’t become apparent until the interpreter executes the code.
JavaScript, being a scripting language, allows your web page to 'think'. It allows developers to add increased interaction, information processing, and control in web-‐based content.
What are the tools needed?
All that is need is:
1. A plain text editor, 2. A web browser.
Where to embed JavaScript?
Inside HTML
You can place the JavaScript between <script> tags inside the HTML document. It can be added in the <head> section especially function definitions. It can also be added inside the body.
<!DOCTYPE html> <html>
<head> <script type="text/javascript">
JavaScript goes here... </script>
</head>
Intake 33 -‐ OS Julie Iskander 2012-‐2013
3
<body> Mark-‐up goes here...
</body> </html>
In External file
A better technique is to place your JavaScript code into a separate file. The file is saved with extension .js. It will contain only JavaScript code. The HTML file will only link to that file, using the src attribute in <script> tag.
<!DOCTYPE html> <html>
<head> <script type="text/javascript" src="file.js"> </script>
</head> <body>
Mark-‐up goes here... </body>
</html>
any script written inside the <script> tag now, will be ignored.
iiiJAVASCRIPT SYNTAX
Statements Statements in JavaScript are the building blocks of any script. JavaScript is case-‐sensitive. Statements are separated, by placing them on different lines.
first statement second statement
If a number of statements are on the same line, you must separate them with semicolons.
first statement; second statement; It is good programming practice to place a semicolon at the end of every statement.
first statement; second statement;
Comments Comments are statements that are ignored by the JavaScript interpreter. Comments are used to document and note your code. There are two types of
Intake 33 -‐ OS Julie Iskander 2012-‐2013
4
comments. The first is single-‐line comments ‘//’ // Note to self: comments are good.
The other type is when you want to comment out multiple lines ‘/*……..*/’ /* Note to self: comments are good */
ivVariables Variables are used to store data. Data stored in a variable can be changed multiple times. To use a variable, you must: 1. Declare a variable. 2. Initialize it.
To declare a variable use ‘var’ , you don’t need to set the data type. Example: var a; var a2; var flag; Initializing can be done in the same step of declaring the variable or on a separate step after declaring it. Several variables can be declared in one statement separated by commas. Example: var a=2; var a2; a2=”Hello All!!”; var flag=true; var b=4, name=”Smith”, f; N.B. In JavaScript, if you assign a value to a variable that hasn’t yet been declared, the variable is declared automatically. Although declaring variables beforehand isn’t required in JavaScript, it’s still good programming practice. Variable names can contain only letters, numbers, dollar symbols, and underscores.
Dialogues and Alerts
There are three types of dialogue boxes supported in all major browsers: alert() , confirm() , and prompt(). All of these are members of the window object, but, like
Intake 33 -‐ OS Julie Iskander 2012-‐2013
5
all members of window, can just be accessed by name directly, or with the window prefix.
alert()
alert() is a very basic modal notice box with a message inside it. By modal I mean what the user cannot interact with the browser or proceed in any way until acknowledge the message by clicking Ok.
alert(‘Hello All’);
gives:
This box will look different depending on the user ’ s operating system and browser, and you cannot customize its look and feel.
confirm()
confirm() gives the user a simple binary choice, OK or Cancel. The return of the statement is true or false. True if Ok was pressed, and false if Cancel was pressed.
var result=confirm(‘Are you sure?’);
Execution of the expression will temporarily suspend until the user closes the dialogue.
Intake 33 -‐ OS Julie Iskander 2012-‐2013
6
prompt()
prompt() allow users to input some text that will be sent to the JavaScript code. The prompt() method takes two arguments:
prompt(Question, DefaultValue)
The Question is the message text that will be shown above the text box.
The DefaultValue argument will be the starting text inside the text box. If you don’t want any text in the text box, leave this as an empty string (don’t leave it out, though).
If OK is pressed, the dialogue will return a string containing the text typed by the user. If Cancel is pressed, it will return null
prompt(‘What is your name?’, ‘Type your name’);
vi Data Types Primitive Data Types: Any value that you use is of a certain type. In JavaScript, there are the following primitive data types: 1. Number: includes floating point and integers,
for example 1, 100, 3.14. 2. String: any number of characters,
for example "a", "one", "one 2 three". 3. Boolean: can be either true or false. 4. Undefined: when accessing a variable that doesn't exist (not yet declared) or a declared variable but not initialized.
5. Null: special data type that can only one value, the null value. It means no value, an empty value, nothing.
Strings must be enclosed in single quotes or double quotes.
Intake 33 -‐ OS Julie Iskander 2012-‐2013
7
var mood = 'happy'; var mood = "happy";
If your string contains the double-‐quote character, then it use single quotes to enclose the string and vice-‐versa or use escaping with ‘\’.
var mood = "don't ask";
N.B. Whether you decide to use double or single quotes, it’s best to be consistent. Changing your usage makes your code less readable. The difference between null and undefined is that if a variable has a value null, it is defined but has a value that is nothing. Any value that doesn't belong to one of the five primitive types listed above is an object. Even null is considered an object, having an object (something) that is actually nothing. Programming languages that require explicit typing are called strongly typed languages. Because typing is not required in JavaScript, it is a un-‐typed language. This means that you can change the data type of a variable at any stage. Example:
var age = "thirty three"; age = 33;
Infinity It represents a number too big for JavaScript to handle. Infinity is indeed a number. The biggest number JavaScript can handle is 1.7976931348623157e+308 while the smallest is 5e-‐324. NaN It is "Not A Number", You get NaN when you try to perform an operation that assumes numbers but the operation fails. For example, if you try to multiply 10 by the character "f", the result is NaN. Operators Arithmetic Operators
Intake 33 -‐ OS Julie Iskander 2012-‐2013
8
Logical Operators They work with boolean values.
Intake 33 -‐ OS Julie Iskander 2012-‐2013
9
1. ! —logical NOT (negation) 2. && —logical AND 3. || —logical OR
Comparison Operators
Intake 33 -‐ OS Julie Iskander 2012-‐2013
10
Useful Built-‐in Functions
Intake 33 -‐ OS Julie Iskander 2012-‐2013
11
JavaScript Objects
Date Object
It is used for manipulating date and time. The Date object provides a number of methods for getting or setting specific information about the date and time. The date is based on the UNIX date starting at January 1, 1970 (in Greenwich Mean Time3 [GMT]), and doesn’t support dates before that time.
Because client-‐side JavaScript programs run on a browser, the Date object returns times and dates that are local to the browser, not the server.
We declare a variable with Date object use Date constructor function. If no arguments are passed to the Date object constructor, it returns the local date and time
Example:
var d=new Date() // Date {Sun Dec 30 2012 17:16:21 GMT+0200 (EET)}
There are five formats that can be passed as arguments when creating a Date object;
new Date("Month dd, yyyy hh:mm:ss")
Intake 33 -‐ OS Julie Iskander 2012-‐2013
12
new Date("Month dd, yyyy") new Date(yy,mm,dd,hh,mm,ss) new Date(yy,mm,dd) new Date(milliseconds)
Example:
mydate = new Date() mydate = new Date("March 15, 2010 09:25:00") mydate = new Date(“March 15, 2010”) mydate = new Date(10,2,15) mydate = new Date(10,2,15,9,25,0) mydate = new Date(500);
Intake 33 -‐ OS Julie Iskander 2012-‐2013
13
Intake 33 -‐ OS Julie Iskander 2012-‐2013
14
Math Object
Math is a little different from the other built-‐in global objects.
It's not a normal constructor function and therefore cannot be used with ‘new’ to create objects. Math is a built-‐in global object, which provides a number of methods and properties that are useful for mathematical operations, but can’t be instantiated.
Math's properties are constants so you can't change their values. Their names are all in upper case to emphasize the difference between them and a normal variable property.
Intake 33 -‐ OS Julie Iskander 2012-‐2013
15
Math Properties
Math Methods:
Intake 33 -‐ OS Julie Iskander 2012-‐2013
16
vArrays
An array is a grouping of multiple values under the same name. Each one of these values is an element of the array.
An array can be declared in one of the following ways:
var myarr=[]; //declaring an array literal var myarr=[1 , 2 , ‘three’,’four’,false]; var myarr= new Array() //using array constructor.
Intake 33 -‐ OS Julie Iskander 2012-‐2013
17
var myarr=new Array(2) //an array with 2 undefined elements var myarr=new Array(1,2,’r’,true); //an array with 4 elements
Specifying the number of elements is optional. You can declare an array with/without a number of elements:
Adding elements to an array is called populating. When you populate an array, you specify not just the value of the element and the index of the element, i.e the number of the element starting from 0.
array[index] = element;
Example: var myarr=[] myarr[0]=1; myarr[3]=’Hello’; myarr[6]=false;
This example makes our array of 7 elements, only 3 has values while the rest are undefined.
[1, undefined, undefined, "Hello", undefined, undefined, false]
To retrieve an element from the array you use the index.
Example: var x=myarr[0]; //x will be 1 var y=myarr[3]; //y will be ’Hello’
To delete an element of the array
delete array[index]
Example: delete myarr[3]
[1, undefined, undefined, undefined, undefined, false]
The element in one array can be another array (Array of arrays).
Example: var a = [1, "two", false, null, undefined]; // [1, "two", false, null, undefined] a[5] = [1,2,3]; //another array [1, 2, 3] //a= [1, "two", false, null, undefined, [1, 2, 3]]
To create a 2D array
Intake 33 -‐ OS Julie Iskander 2012-‐2013
18
var a = [[1,2,3],[4,5,6]]; // ar[0]= [1, 2, 3] //ar[2]=[4,5,6]
To access an element in the nested array, you refer to the element index in another set of square brackets.
a[0][0]=1 ar[1][2]=6
To access individual characters inside a string, use array notation.
var s = 'one'; // s[0]="o" //s[1] ="n" //s[2] ="e"
Arrays can be views as a key/value pair. For example myarr array can be viewed as:
Key Value 0 1 1 undefined 2 undefined 3 ‘Hello’ 4 undefined 5 undefined 6 false
which leads us to associative arrays.
Associative arrays (Hash)
The index of elements can be a string instead of numbers:
Example: var students = Array(); students["Ahmed"] = 22; students["Mohamed"] = 33; students["Ibrahim"] = 44;
Key Value Ahmed 22 Mohamed 33 Ibrahim 44
This is the way JavaScript create and store objects as will be shown in the Objects section.
Intake 33 -‐ OS Julie Iskander 2012-‐2013
19
To refer to elements use keys instead of index.
var x= students["Ahmed"]
Example: var students = Array(); var std=[]; std[‘name’]=’Ahmed’ std[‘age’]=20; std[‘total’]=200; students[0]= std; var std=[]; std[‘name’]=’John’ std[‘age’]=22; std[‘total’]=220; students[1]= std; var std=[]; std[‘name’]=’Mona’ std[‘age’]=20; std[‘total’]=230; students[2]= std;
Now to get name of second students, students[2][‘name’]. It can be accessed also by dot notation, students[2].name
N.B. Use square brackets when keys contain spaces or are reserved words.
Array Properties
length: returns the number of elements in the array.
Array Methods
Intake 33 -‐ OS Julie Iskander 2012-‐2013
20
VControl Statements
Conditionals
Conditional statements are used when decisions need to be made and branching of code occurs.
1. if……else
if (condition) {
statements; }
The condition is contained within parentheses. The condition always resolves to a Boolean value (true/false).
The statement or statements contained within the curly braces will be executed if and only if the result of the condition is true.
Example:
Intake 33 -‐ OS Julie Iskander 2012-‐2013
21
var x=prompt("Enter a number less than 100",0); x=parseInt(x); if(isNaN(x) || x>100) { alert('Wrong Answer')
}
The alert will only be shown if x is not a number (i.e. user entered letters instead of numbers), or x is greater than 100.
The if statement can be extended using else.
if (condition) {
statements; } else { statements }
Example:
var x=prompt("Enter a number less than 100",0); x=parseInt(x); if(isNaN(x) || x>100) { alert('Wrong Answer')
} else
{ alert(‘Correct Answer');
}
Now if the condition is false the other alert appears. Nested if…..else is also supported.
Example: var x=prompt("Enter a number less than 100",0); x=parseInt(x); if(isNaN(x)) { alert('Wrong Answer.\nPlease enter a valid number') } else { if(x>100) alert('Wrong answer.\n Please enter a number < 100');
Intake 33 -‐ OS Julie Iskander 2012-‐2013
22
else alert('Correct Answer') }
2. Switch Replaces if when checking for multiple equalities.
switch (expression) { case expression1:
statements break;
case expression2: statements break;
default: statements break;
} The expression most often contains a variable, but can be anything that returns a value. Each case statement is followed by an expression. The result of the case expression is compared to the expression placed after the switch statement. If the result of the comparison is true, the code that follows the colon after the case is executed. There is an optional break statement to signal the end of the case block. If this break statement is reached, the switch terminates. Otherwise, if the break is missing, we enter the next case block, which should be avoided. This is called ‘fall-‐through’. Thus, Don't forget to break. There's an optional default statement, which is followed by a block of code that is executed if none of the previous cases evaluated to true. Example:
var a = '1'; var result = ''; switch (a) {
case 1: result = 'Number 1'; break;
case '1': result = 'String 1'; break;
default:
Intake 33 -‐ OS Julie Iskander 2012-‐2013
23
result = 'I don\'t know'; break;
} When executing the code, result="String 1".
Loops
To execute the same block of code a number of times, you’ll need to use a looping statement. The block of code within a looping statement continues to be executed as long as the a specified condition is true. When the condition is no longer true, the loop stops.
1. while
while (condition) {
statements; }
Example: var count = 1; while (count < 11) {
alert (count); count++;
}
This code will alert the numbers from 1 to10.
2. do...while
It is similar to the while loop, except that the condition is tested after executing the code. If the condition is false from the start, the code is executed once. If we used while, the code will never be executed.
do {
statements; } while (condition);
Example:
var count = 1; do
Intake 33 -‐ OS Julie Iskander 2012-‐2013
24
{ count++; alert (count);
} while (count < 11);
The alert message appears ten times. After the loop is finished, the value of the variable count is eleven.
Now consider this variation:
var count = 1; do {
alert (count); count++;
} while (count < 1);
In this case, the condition never evaluates as true. The value of count is one to begin with so it is never less than one. Yet the do loop is still executed once. You will still see one alert message.
3. for
The for loop used for executing some code a specific number of times.
for (initial condition; test condition; alter condition) {
statements; }
Example: for (var count = 1; count < 11; count++ ) {
alert (count); }
The code will be executed exactly ten times.
One of the most common uses of the ‘for’ loop is to act on every element of an array.
var beatles = Array("John","Paul","George","Ringo"); for (var count = 0 ; count < beatles.length; count++ ) {
alert(beatles[count]); }
Intake 33 -‐ OS Julie Iskander 2012-‐2013
25
If you run this code, you will see four alert messages, one for each Beatle.
4. for/in
The ‘for’ keyword, is used in two different ways in JavaScript. It is also used in the for/in statement.
for (variable in object)
statement
The for-‐in loop is used to iterate over the elements of an array (or an object). Let's see an example of using a for-‐in to loop through the elements of an array. Take care that the variable will carry each key/index of each element not the value.
Example:
var a = ['a', 'b', 'c', 'x', 'y', 'z']; var result = '\n'; for (var i in a) {
result += 'index: ' + i + ', value: ' + a[i] + '\n'; }
The result is: " index: 0, value: a index: 1, value: b index: 2, value: c index: 3, value: x index: 4, value: y index: 5, value: z "
The for/in statement provides a way to loop through the properties of an object. The body of the for/in loop is executed once for each property of object. Before the body of the loop is executed, the name of one of the object's properties is assigned to variable, as a string.
Within the body of the loop, you can use this variable to look up the value of the object's property with the [] operator.
For example, the following for/in loop prints the name and value of each property of an object:
Intake 33 -‐ OS Julie Iskander 2012-‐2013
26
for (var prop in my_object) {
document.write("name: " + prop + "; value: " + my_object[prop], "<br>"); }
Functions
A function is a group of statements that can be invoked from anywhere in your code, multiple times.
function name(arguments) { statements; }
Example:
function sum(x,y) { var c=x+y; return c; }
‘sum’ is the function name(optional)
x,y are the function input parameters that are passed to the function on calling it
the return statement states the value returned from the function call.
To call this function
var x=sum(1,2) //x will be 3;
Any arguments that are passed to a function can be used just like regular variables within the function.
If a function was defined to take parameters and was called without them, JavaScript assign the variables with undefined.
If you sent more parameters than defined, JavaScript will just ignore them.
Variable scope
A global variable can be referenced from anywhere in the script. Once a global variable has been declared in a script, that variable can be accessed from anywhere in that script, even within functions. Its scope is global.
Intake 33 -‐ OS Julie Iskander 2012-‐2013
27
A local variable exists only within the function in which it is declared. You can’t access the variable outside the function. It has a local scope.
The is no block scope, only function scope. This means that if a variable is defined inside a function, it's not visible outside of the function. However, a variable defined inside a ‘if’ or a ‘for’ code block is visible outside the code block.
N.B. If you unintentionally use the name of a global variable within a function, JavaScript will assume that you are referring to the global variable. Use the ‘var’ keyword to explicitly set the scope of a variable within a function.
If you use var within a function, the variable will be treated as a local variable. It only exists within the context of the function.
If you don’t use var, the variable will be treated as a global variable.
Take a look at this example:
function square(num) {
total = num * num; return total;
} var total = 50; var number = square(20); alert(total);
The value of the variable total is now 400, which wasn’t intended. Because inside the function total was not declared with ‘var’.
function square(num) {
var total = num * num; return total;
}
N.B. It is good practice to minimize the number of global variables used. Functions are Data They aren’t just excutable code but are objects. Thus can be assigned to variables.
function f(){return 1;} var f = function(){return 1;}
Intake 33 -‐ OS Julie Iskander 2012-‐2013
28
Both definitions are valid. To call the function we use f(); The second way of defining a function is known as function literal notation. Anonymous Functions They are functions without a function name. They can be assigned to variables or callbacks and events. They can be passed as parameters to other functions or you can define an anonymous function and execute it right away.
function(a){return a;}
Example: function invoke_and_add(a, b) {
return a() + b(); } function one() {return 1;} function two() {return 2;} invoke_and_add(one, two);
Or simply: invoke_and_add(function(){return 1;}, function(){return 2;})
When you pass a function A to another function B and B executes A, it's often said that A is a callback function. If A doesn't have a name, then you can say that it's an anonymous callback function. Why use them?
• They let you pass functions without the need to name them (which means there are less global variables)
• You can delegate the responsibility of calling a function to another function (which means there is less code to write)
• They can help with performance
Self-‐invoking Functions Another application of an anonymous function is calling this function right after it was defined. Example:
(function(){alert('boo');})();
Intake 33 -‐ OS Julie Iskander 2012-‐2013
29
Simply place an anonymous function definition inside parentheses followed by another set of parentheses. The second set basically says "execute now" . Example:
(function(name){alert('Hello ' + name + '!');})('dude') Why use this?
Decreases need to create global variables. Suited for one-‐off or initialization tasks.
Drawback: Cannot execute the same function twice (unless you put it inside a loop or
another function). The Global Object The host environment (web browser) provides a global object and all global variables are actually properties of the global object. The global object is called window. For example Declaring
var a = 1; outside of any function, makes it a global variable. Then it can be accessed:
• As a variable a • As a property of the global object,
o window['a'] o window.a
All global functions can also be invoked as methods of the window object. parseInt(‘101’) or window.parseInt('101 dalmatians'). References : i From http://www.crockford.com/javascript/little.html iiFromhttp://web.archive.org/web/20080208124612/http://wp.netscape.com/comprod/columns/techvision/innovators_be.html iii Dom Scripting, Web Design with JavaScript and the Document Object Model, Jeremy Keith, 2005. iv Object Oriented JavaScript, Stoyan Stefanov, 2008, Chapter 2