1 / 32

Javascript Training

Javascript Training. Introduction to Javscript 2 Hours Variables 1 Hour Operators 1 Hour Statements 1 Hour Loops 2 Hour Functions 2 Hour Arrays 1 Hour Total 10 Hours. Introduction to Javascript.

connorm
Télécharger la présentation

Javascript Training

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Javascript Training Introduction to Javscript 2 Hours Variables 1 Hour Operators 1 Hour Statements 1 Hour Loops 2 Hour Functions 2 Hour Arrays 1 Hour Total 10 Hours

  2. Introduction to Javascript • Javascript is the client side scripting language, developed by netscape, used along with HTML to build an efficient web site / webpage. • In the beginning stages, web pages were developed only using html which are nothing but static pages. User interaction and dynamic changes are not possible with html. With the advent of scripting languages, the problem was solved. There are two types of script languages - server side and client side.When a page is requested, the request is sent to the server and data is fetched and viewed in the browser. • If the dynamic changes in the webpage are caused in the client side (the browsers like mozilla / IE) it is called client side scripting language (E.g. - Javascript). • If the dynamic changes in the web page are caused in the server side (the server checks the request and based on the data it makes changes in the page before sending the data to the browser) it is called server side scripting language (E.g. - php). • Java script codes are embedded in HTML files. Whenever a browser requests for a webpage, the HTML file along with script is transferred to the browser. This tutorial will give you an introduction and help you learn java script. • JavaScript is used to create dynamic changes, validate forms, detect visitor details, create/use cookies, etc.. JavaScript works in all major browsers such as Internet Explorer, Mozilla, Firefox, Netscape, Opera, Safari and more.

  3. Introduction to Javascript • Script tag is the primary tag which identifies javascript. Any javascript code should be written in between the script tag. <script language="javascript"> </script> Here the attribute language defines the language used. For VBscript user it will be vbscript. The script tag can be written anywhere inside head or body tag of html. Example: <html> <head></head> <body> <script language=javascript> //code comes here..... //code comes here..... //code comes here..... </script> </body> </html>

  4. Introduction to Javascript First Javascript program using document.write? We will begin with the in built method or function document.write() to code our first javascript program. This method helps to write any given variable on the browser. Example: <html> <head></head> <body> <script language=javascript> document.write("This is my first javascript program"); </script> </body> </html>

  5. Introduction to Javascript HTML tags or code can also be added using document.write method. i.e. Just use the html code as the argument for document.write or document.writeln functions document.write("-- bold red --"); Example Code: <script language=javascript> document.write("-- <b>bold</b> <font color=red> red </font>--"); </script> Result: -- bold red -- Break line for .write method : document.write will append the string to the previous string. i.e. if you call document.write(" -- first line ---"); document.write(" -- second line ---"); the result will be as " -- first line --- -- second line ---"; So in order to break the lines in the browser you have to use an additional code "<br>" at the end. e.g: document.write(" -- first line --- <br>"); Example Code: <script language=javascript> document.write(" -- first line --- <br>"); document.write(" -- second line --- <br>"); </script> Result: -- first line --- -- second line ---

  6. Introduction to Javascript • The in built function alert can be used for creating a alert or popup message. • Use the function with any string as argument. • Example: • <script language=javascript> • alert("This is a test alert message"); • </script>

  7. Variables Variables are used to store values. i.e. for example if we have to add two numbers, we will declare two variables and assign the numbers to each variable and add them to get the result. var a = 5; var b= 5; var c = a+b; Javascript can handle the following variable types a) Number (Integer and Float) b) String c) Boolean d) Null e) Undefined In javascript all variable types are declared as var, only depending on how we assign the values the data type is defined. var a = "as"; --> This is a string type variable var a = 2; --> This is a integer type variable var a = true; --> This is a boolean type variable Here var defines it as a variable. "a" is the variable name. "as", 2, true are called values. The variable name can have alphanumeric values. Any lowercase (a-z) or uppercase (A-Z) alphabets, numbers (0-9) or underscore(_).

  8. Variables String- E.g: "sdfesdfe" For a variable to be a string type, the value assigned should be given in quotes. A number given within quotes will be considered only as a string and not as an integer. i.e if var a = "2"; var b = "2"; then a+b will give "22" and not 4. Example Code: <script language="javascript"> var as = "this is \"a\" \'test\'"; document.write(as); </script> Result: this is "a" 'test' Number: Numbers can be used in two different types in javascript. They are integer and float. Integer- E.g: 2 For a variable to be of int type just assign number with out any quotes. i.e if var a = 2; var b = 2; then a+b gives 4. Float- E.g: 2.12 For a variable to be of float type just assign fractional number with out any quotes. i.e if var a = 2.12; var b = 2.12; then a+b gives 4.24

  9. Variables Boolean Data Type- E.g: true It can have logical values true or false. Variable type Boolean should not have any quotes. i.e. "true" is not equal to true, "true" will be considered as a string. var a = true; var b = false; Boolean variable values are mostly used along with "if", "if else" statements and "while" loops. Example Code: <script language="javascript"> var a = true; if(a == true) { document.write("this is true"); } </script> Result: this is true Data Type Conversion: The following data type conversions are possible a) String to Integer (int) b) Float to Integer (int) c) String to Float d) Integer (int) to String e) Float to String a) Converting String to Integer To convert a value from string to integer we have to use the function or method "parseInt(). Passing a correct argument to the function (e.g: "4") will return correct value else (e.g: "sd") 0 will be returned. b) Converting Float to Integer To convert a float value in to integer we have to use the function or method parseInt. parseInt(5.133) -> 5

  10. Operators • ExplanationAn operator is a symbol or sign used in javascript to identify a specific operation.For example, when we want to define an expression for adding two numbers, we use 3+4. Here let us assume that we have defined variable a and b for the number, so the expression will become a+b; The symbol "+" defines that the operands a and b has to be added. So "+" is called as an operator.Types:There a three type of operators based on operands used, namely unary, binary, ternary.Unary - This works with one operand (e.g: a++, a will be incremented by 1),Binary - This works with two operands (e.g: a+b),Ternary - This works with three operands (e.g: condition? value 1 : value 2).

  11. Operators • Arithmetic Operators: They are operators or syntax used to do arithmetic or math operations like addition, subtraction, multiplication, division, increment, decrement, etc.. These are some time misspelled as arithmatic, arithematic.

  12. Operators Arithmetic Operators: They are operators or syntax used to do arithmetic or math operations like addition, subtraction, multiplication, division, increment, decrement, etc.. These are some time misspelled as arithmatic, arithematic. + Used for addition of two numbers - Used for subtraction of two numbers * Used for multiplication of two numbers / Used for division of two numbers % Used to find the division remainder ++ Used to increment a value -- Used to decrement a value Example Code: <script language="javascript"> var c = (2+4-2)*10; document.write(" Arithmetic Operations -> "+c); </script> Result: Arithmetic Operations -> 40

  13. Operators Logical Operators: There are used mainly for boolean operations. Operator Syntax Description && Used for logical "and" operation, condition || Used for logical "or" operation, condition ! Used for logical "not" operation, condition Local operators or used along with if statements and while loops to check multiple criterias. example usage1: if a is animal && (and) b is man, print something. example usage2: if a is tany || (or) a is ramani, say good morning. Example Code: <script language="javascript"> var a = "tany"; var b = "ramani"; if(a == "tany" && b == "ramani") { document.write(" Logical Operator AND '&&', OR '||', NOT '!' "); } </script> Result: Logical Operator AND '&&', OR '||', NOT '!'

  14. Operators Comparison Operators: They are used to compare numerical (numbers), string or boolean values. Operator-Syntax Description == validates the condition whether two numbers or string values are equal != validates the condition whether two numbers or string values are not equal > validates the condition whether one numbers is greater than other < validates the condition whether one numbers is less than other >= compares the numbers and checks whether one numbers is greater than or equal to other <= compares the numbers and checks whether one numbers is less than or equals other === used to compare and check whether two values are strictly equal !== used to compare and check whether two values are strictly not equal The main difference between "equal to (==)" and "strictly equal to (===)" is that the equality comparison takes place after type conversion for "equal to (==)" and before type conversion for "strictly equal to (===)". i.e "5" == 5 and "5" !== 5 Example Code: <script language="javascript"> var a = "5"; var b = 5; if(a == b) { document.write(" Testing Comparative Operator for equals "); } if(a === b) { document.write(" Testing Comparison Operator for strictly equals "); } </script> Result: Testing Comparative Operator for equals

  15. Operators Assignment Operators are use to assign a value to a variable. = used to assign a value on the right side to the variable of the left side of the operator. b = 3; += it adds the value on the right to the previous value of the variable on the left and assign the new value to the variable. b = 3; b += 4; // Now b will become 7 -= it subtracts the value on the right to the previous value of the variable on the left and assign the new value to the variable. b = 4; b -= 2; // Now b will become 2 *= it multiplies the operand on the right to the previous value of the variable on the left and assaigns the new value to the variable. b = 4; b *= 2; // Now b will become 8 /= it divides the operand on the right to the previous value of the variable on the left and assaigns the new value to the variable. b = 6; b /= 2; // Now b will become 3 <<= The operand on the left is shifted left by the value on the right. <<= A signed right shifted is performed on the left operand by the value on the right.

  16. Operators Ternary Operator: As the name indicates ternary operators take three operands. The syntax is condition ? result1 : result2;. Here you use a condition before question mark (?) followed by result 1 and result 2 separated by a colon (:). Result1 is called if the condition is satisfied else result2 is called. Example 1: <script language=javascript> var b=5; (b == 5) ? a="true" : a="false"; document.write(" --------------------------- "+a); </script> Result: --------------------------- true Example 2: <script language=javascript> var b=true; (b == false) ? a="true" : a="false"; document.write(" --------------------------- "+a); </script> Result: --------------------------- false

  17. Statements If statement is used to check or verify a condition and execute a set of statement only if the condition is true. This should be referred as a statement and not as a function. Syntax: if(condition) { // set of statements that will be executed // only if the condition is true or satisfied } Example Code: <script language="javascript"> var a = "if check"; if(a == "if check") { document.write(" inside if statement "); } </script> Result: inside if statement In the above example the condition is to check whether variable 'a' equals (==) the string "if check". As the condition satisfies, the statements inside the brackets are executed. Nested If: Nested if statement is nothing but using an if statement inside another if statement. Nested if is used when we check a condition only when another condition is true. For an example when we purchase a car, first we verify is the car looks good, only if it satisfies we go to the next condition color, then next and so on.. Syntax: Nested if if(condition 1) { if(condition 2) { // set of statements that will be executed } }

  18. Statements If else statement also has the same format as that of "if" statement. Only additional thing is that an else part is added to if statement. So if the condition satisfies the statements inside if part will be executed else the statement inside else part will be executed. Syntax: if(condition){ // set of statements if condition satisfies } else{ // set of statements if condition fails } Example Code: <script language="javascript"> var a = "1234abc"; if(a == "adcdefa"){ document.write(" inside if statement "); }else{ document.write(" inside else part of statement "); } </script> Result: inside else part of statement In the above example the condition is to check if variable 'a' equals (==) "abcdefa". The condition fails as we have assigned a as "1234abc". So the else part is executed.

  19. Statements "with" statement is used when numerous function of an object is used or a function of an object is to be used numerous times. Syntax: with(object) { // Calling the functions or methods of the object } For this example we will use the object "document" and its methods (functions) "write" and attribute "title". Example Code: <script language="javascript"> with(document) { write(" inside with statement <br>"); write(" using with(object) we can call its functions directly <br>"); write (" TITLE -"+title); } </script> Result: inside with statement using with(object) we can call its functions directly TITLE - With Statement Code - Javascript (JS) Tutorial In the above example you can clearly see that the write function is executed numerous times with out calling document.write() and also title (document.title) is called. You can use any objects with "with" statement. e.g: date, math, etc.

  20. Loops for LOOP: As we state it, for loop is a looping syntax. A set of statements are executed as a loop until a condition is satisfied, the condition is based on an incremental or decremental counter. In other words "Looping statements in javascript are used to execute the same set of code a specified number of times". Syntax: for(intialvalue; condition; increment) { // set of statements that will be executed } As defined in the syntax, for loop takes three parameters, the initial value (e.g i=0), condition - the statements inside "for" will be executed until this condition is satisfied (e.g i<7), increment - this is where we set the initial value to be increased or decreased after each loop. All the three parameters are separated by semicolon ";". For an example, we will consider a situation where we want to add all numbers between one and ten. Example Code: <script language="javascript"> var i=0; var total=0; for(i=1; i<11; i++) { total = total+i; } document.write("--------- The total ------: "+total); </script> Result: --------- The total ------: 45 The example worked as follows, a) Initially we created the for loop by setting variable i as 1. b) then we set the condition that the loop should execute till i is less than 11 (i<11). c) We made the variable to be incremented at the end of each loop (i++) First loop: i=0, i<11 is true so the statement is executed, now the total becomes 0+1=1 and i is incremented to 2. Second loop: now i=1, i<11 is true so the statement is executed, now the total becomes 1+2=3 and i is incremented to 2. this continues till i=11 Last loop: now i=11, i<11 becomes false and the loop ends here. Note: i++ increments the value at the end on the loop, while ++i to increase the value of i at the start of the loop.

  21. Loops Switch case is used to when a condition may have multiple results and a different set of operation is done based on each result.. Syntax: Switch(condition) { case result1: // Operation for result1 case result2: // Operation for result2 default : // If result belongs to none of the case specified } Example Code: <script language="javascript"> for(var i=1; i<5; i++) { switch(i) { case 1: document.write("message for case 1 <br>"); break; case 2: document.write("message for case 2 <br>"); break; case 3: document.write("message for case 3 <br>"); break; default: document.write("message for case default<br>"); break; } } </script> Result: message for case 1 message for case 2 message for case 3 message for case default In the above example we have used for loop to explain switch case statement. Here each time the value of i is different and increases as 1, 2, 3, 4. There are three case defined for 1, 2, 3. When value is 4, default is executed.

  22. Loops 'while' loop is used to execute a set of statements repeatedly until a condition works true. The difference between 'for' and 'while' loop is that 'while' does not take counter as an argument. Syntax: while(condition) { // set of statements that will be executed } As defined in the syntax, while loop has only one parameter, condition to be validated. The statements inside "while" will be executed until this condition becomes false. For an example, we will consider a situation where we want to print first 5 number. Example Code: <script language="javascript"> var i=0; while(i<5) { document.write("The value of i is - "+i+" "); i++; } </script> Result: The value of i is - 0 The value of i is - 1 The value of i is - 2 The value of i is - 3 The value of i is - 4 The execution process is as, a) The initialization of the variable "i" as 1 was done before starting the loop. b) In while loop, the condition was checked, the condition is satisfied (true) as i<5 and so the statements are executed. c) In the last line of the statement we has increased or incremented the value of i by 1. So after the end of the loop the pointer goes back to the beginning of the loop and checks the condition. d) Now "i" will be 1 and i is less than 5. The condition satisfies and the statements are executed. This continues till i is 5. e) When i is five, the condition becomes false and the pointer comes out of the loop. Note: The very important thing to note here is the i++ statement. If i++ has not been included 'i' will always be zero, so the condition will always be true and the loop becomes an infinite loop. This will cause memory issue or infinite loading of the page.

  23. Loops •   'do-while' loop is similar to while loop and the only difference here is that the set of statements are executed first and the condition is checked next.Syntax:do{     // set of statements that will be executed }while(condition)Here the statements are added under do loop and while condition is checked at the end of loop. In 'Do While' the statements are executed once even if the condition will fail. An exampleExample Code:<script language="javascript">var i=0;do{document.write("Testing DO-While loop");}while(i!=0)</script>Result:Testing DO-While loop • In the example the condition is 'i' should not be equal to zero. The statements are executed and the condition is checked. The condition failed. The pointer comes out of the loop. So the statements are executed once even when the condition fails. 

  24. Loops Break is a statement used to exit or terminate a loop in execution. It is used in "for, while, do-while" looping statements. Break statement is used mostly with a conditional statement inside the loop. When the condition satisfies the control breaks/terminates from the loop and moves to the next line below the loop. For an example, we will use a for loop that prints 1 to 5 but will use break or exit the loop iteration when i is 3. Example Code: <script language="javascript"> for(var i=0; i<5; i++) { if(i == 3) break; document.write("i is - "+i); } document.write(" --------- After Looping------ "); </script> Result: i is - 0 i is - 1 i is - 2 --------- After Looping------ The example worked as follows, a) "for loop" has five iterations from i=0 to i=4. b) It executes document.write at every iteration for i=0,i=1,i=2. c) when i is 3 the condition above document.write becomes true and so it is called. d) break statement exits or terminates the looping sequence and brings the control to the line next to the end of loop.

  25. Loops Continue statement is used to stop or terminate one iteration of the loop in execution. It is used in "for, while, do-while" looping statements. Continue statement unlike break statement does not completely terminate the loop. It stops processing for only one iteration and brings the control back to the beginning of the loop. For an example, we will try to stop processing inside a for loop when i is 2. Example Code: <script language="javascript"> for(var i=0; i<5; i++) { if(i == 2) continue; document.write("i is - "+i); } </script> Result: i is - 0 i is - 1 i is - 3 i is - 4 The example worked as follows, a) This for loop has five iterations from i=0 to i=4. b) It executes document.write at every iteration. c) when i is 2 the condition above document.write becomes true and so it is called. d) continue statement terminates the looping sequence and brings the control to the beginning of loop, starting the next iteration. e) Thus the print was not done for i as 2.

  26. Functions A function is nothing but a group or block of statements doing a specific task. Syntax: function name() { // set of statements that will be executed } A function has to be defined in the above syntax. The name "function" followed by the name we choose for the function and then open and close brackets. The statements that will do the specific operation are then group together under this name using braces. A function may or may not return a value. A function may or may not have parameters value. Invoking a function: The statements inside the function will not be executed automatically. We have to invoke or call the function to execute the statements. Just calling the name of the function will invoke the function. i.e. if we write a function with the name "test" calling it as "test();" will invoke the function. Example Code: <script language="javascript"> function test() { document.write(" ---- This is a test function ---- "); } test(); </script> Result: ---- This is a test function ----

  27. Functions function name(parameter 1,parameter 2,...) { // set of statements that will be executed } In many cases we pass parameters or arguments to functions, these arguments will be used inside the function for required calculations. For an example we will use two numbers to add, subtract using function. Here we write separate function for each operations add, subtract. Example Code: <script language="javascript"> function add(number1, number2) { var c = number1+number2; document.write(" ---- This added value is ---- "+c; } function sub(number1, number2) { var c = number1-number2; document.write(" ---- This subtracted value is ---- "+c; } var a = 7; var b = 3; add(a,b); sub(a,b); </script> Result: ---- This added value is ---- 10 ---- This subtracted value is ---- 4 Here you can clearly see that the two functions where invoked as "add(a,b);" and "sub(a,b);" where a and b are defined variables. You can even call the function directly with the variables as say "add(9,1);". A function can be invoked any number of times with any proper value.

  28. Functions function name(parameter 1,parameter 2,...) { // set of statements that will be executed return thevalue; } A function can also return a value after doing the specified operations. To explain, we would consider a requirement where we have to calculate x2/2. We will calculate x2 in a function and return the result of x2. After getting the return value, we will divide it by 2. Example Code: <script language="javascript"> function square(number1) { var c = number1*number1; // Now we will return the result return c; } var x = 4; // Here we invoke the function and capture the result var des = square(x); var res = des/2; document.write(" The result - "+res); </script> Result: The result - 8 In the above example we calculate x2 in the function "square(xxx)". We returned the result. Getting the Result: As the function is to return a value, while we invoke the function we assigned a variable to capture the result as "var des = square(xxxx);". Now the result of x2 is assigned to the variable des. Using the variable 'des' further operations were completed. Note: Once the return statement is called in a function it will break, i.e no further statements below it will be executed.

  29. Functions An object is nothing but a class or file with a group of functions or methods. In javascript strings are stored as string objects. We can declare a string in either of the two ways a) var sname = "testing string object"; b) var sname = new String("testing string object"); Both results in the same string object. String object contains some predefined function or methods that are extensively used in javascript. String object has the following functions a)length() b)charAt() c)indexOf() d)lastIndexOf() e)substring() f)split() g)toLowerCase() h)toUpperCase()

  30. Functions Object: String Method or Function: length Description: This will count the total number of characters (length or size) present in the string and returns the value. Example Code: <script language=javascript> var ss = "a character count - size test "; var result = ss.length; document.write(result); </script> Result: 30 Explanation: In the above example, the string is stored in a variable ss. then the function is called as "ss.length". the method counts the total characters in the string and returns it. the result is of variable type, integer.

  31. Arrays They are special type of javascript objects. It is used to store data's in contiguous manner. In other words arrays help you to store similar data's under one name in a defined order. Syntax: var varname = new Array(3); In the above syntax we have declared a new array of size 3 under the name varname. We can create new array only using the syntax new Array. It is case sensitive and so "Array" should not be defined as "array". The size of the array is set as 3. So, we can store 3 variables in the array varname. It can be declared with any size according to our requirement. Assigning Vales: Arrays always start from 0th index or position. If we have set the size as 3, the array will have 3 position 0,1 & 2. We can assign values as follows, varname[0] = "testing array"; varname[1] = "position 2"; varname[2] = "position 3"; To assign a value in to an array, we have to call the variable name on which the array was created, followed by the position [where we want to store the value] and then assign the value. Retrieving Values: To retrieve a value from an array is very simple. Just calling the array with its position will retrieve the value at that position. E.g: var val = varname[0]; Example Code: <script language="javascript"> var varname = new Array(2); varname[0] = "testing array"; varname[1] = "position 2"; document.write("Result of array is - "+varname[1]); </script> Result: Result of array is - position 2 The above example shows how to create a new array of size two, add values in to it and retrieve them. In next tutorial chapter, you will learn dense and dynamic array..

  32. Arrays Array has the following predefined methods. toString() join() reverse() sort() Method: toString() : This method is used to convert the array elements in to a string. The string will have each element in the array separated by comma(,). Example Code: <script language="javascript"> var varname = new Array(); varname[0] = "testing to string 1"; varname[1] = "testing to string 2"; document.write("toString -- "+varname.toString()); </script> Result: toString -- testing to string 1,testing to string 2 Method: join() : This method is used to join the elements in the array separated by a separator. This function is much similar to toString method. Here we can specify the delimiter or separator that comes instead of comma. Example Code: <script language="javascript"> var aarray = new Array(); aarray[0] = "element 1"; aarray[1] = "element 2"; var xx = aarray.join(" +++ "); document.write("join() -- "+xx); </script> Result: join() -- element 1 +++ element 2

More Related