2 Working with JavaScript JavaScript concept or What is JavaScript? JavaScript is the programming language of the Web. It is an object-oriented language that allows creation of interactive Web pages. It is most commonly used as part of web browsers, whose implementations allow client-side scripts to interact with the user, control the browser, communicate asynchronously, and alter the document content that is displayed. It is also used in server-side network programming with runtime environments. Javascript is an implementation of the ECMAScript language standard. ECMA-262 is the official Javascript standard. JavaScript is: JavaScript is a lightweight, interpreted programming language Designed for creating network-centric applications Complementary to and integrated with Java Complementary to and integrated with HTML Open and cross-platform It is case sensitive scripting language. Origin of JavaScript JavaScript was released by Netscape and Sun Microsystems in 1995. However, JavaScript is not the same thing as Java. JavaScript and Java are completely different languages, both in concept and design. Brendan Eich developed JavaScript for Netscape in the 90s, and it was included with an early version of Netscape 2 in 1995 and became an ECMA standard in 1997. During development JavaScript was called Mocha and then LiveScript. Why we use and learn JavaScript? JavaScript is one of the 3 languages all web developers must learn: 1. HTML to define the content of web pages 2. CSS to specify the layout of web pages 3. JavaScript to program the behavior of web pages Advantages of Javascript Speed: Being client-side, JavaScript is very fast because any code functions can be run immediately instead of having to contact the server and wait for an answer. Less server interaction: You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server. Simplicity: JavaScript is relatively simple to learn and implement. 1 Dept: CE DWSL (3360705) Ravi G. Shrimali
Versatility: JavaScript plays nicely with other languages and can be used in a huge variety of applications. Unlike PHP or SSI scripts, JavaScript can be inserted into any web page regardless of the file extension. JavaScript can also be used inside scripts written in other languages such as Perl and PHP. Server Load: Being client-side reduces the demand on the website server. Immediate feedback to the visitors: They don't have to wait for a page reload to see if they have forgotten to enter something. Richer interfaces: You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors. Easy Debugging and Testing: Javascript are tested line by line and the errors and the errors are also listed as they are encountered so it is easy to locate errors, make changes, and test it without the overhead and delay if compiling. JavaScript Syntax A JavaScript consists of JavaScript statements that are placed within the <script>... HTML tags in a web page. You can place the <script> tag containing your JavaScript anywhere within you web page but it is preferred way to keep it within the <head> tags. The <script> tag alert the browser program to begin interpreting all the text between these tags as a script. So simple syntax of your JavaScript will be as follows: Syntax: <script language="javascript" type="text/javascript"> JavaScript code The script tag takes two important attributes: language: This attribute specifies what scripting language you are using. Generally, its value will be javascript. type: This attribute is what is now recommended to indicate the scripting language in use and its value should be set to "text/javascript". <html> <head> <title>javascript Program</title> <script language="javascript" type="text/javascript"> document.write("hello World!"); </head> </html> 2 Dept: CE DWSL (3360705) Ravi G. Shrimali
Hello World! Javascript Variables JavaScript variables are containers for storing data values. You can place data into these containers and then refer to the data simply by naming the container. Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows: var money; var name; Use the var keyword only for declaration or initialization. You should not re-declare same variable twice. JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type. Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of value the variable will hold. JavaScript Variable Scope The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes. Global Variables: It has global scope which means it is defined everywhere in your JavaScript code. Local Variables: It will be visible only within a function where it is defined. Function parameters are always local to that function. Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable. Following example explains it: <html> <head> <title>javascript Program</title> var demo = "global"; // Declare a global variable function checkscope( ) var demo = "local"; // Declare a local variable </head> <body> document.write(demo); 3 Dept: CE DWSL (3360705) Ravi G. Shrimali
<button onclick="checkscope();">click Me</button> </body> </html> The Above example will produces the following result as an output: local JavaScript Identifiers All JavaScript variables must be identified with unique names. These unique names are called identifiers. JavaScript identifiers are case-sensitive. The general rules for constructing names for variables (unique identifiers) are: Names can contain letters, digits, underscores, and dollar signs Names must begin with a letter Names can also begin with $ and _ Names are case sensitive (a and A are different variables) Reserved words (like JavaScript keywords) cannot be used as names JavaScript Reserved Words The following are reserved words in JavaScript. They cannot be used as JavaScript variables, functions, methods, loop labels, or any object names. Javascript Data Types The DataType is a classification of the type of data that a variable or object can hold in computer programming. JavaScript allows you to work with three primitive data types: Numbers, Strings and Boolean. Numbers: Numbers in JavaScript are represented in 64-bit floating-point format. JavaScript makes no distinction between integers and floating-point numbers. For example: 1 3.14.0001 6.02e23 4 Dept: CE DWSL (3360705) Ravi G. Shrimali
Strings: String literals appear in JavaScript programs between single or double quotes. One style of quotes may be nested within the other. For example, 'name ="MyData" '. 'testing' "3. 14" "Wouldn't you prefer O'Reilly's book?" Boolean: the Boolean type has two possible values, represented by the JavaScript keywords true and false. JavaScript also defines two trivial data types: null and undefined, each of which defines only a single value. null: The JavaScript keyword null is a special value that indicates "no value". undefined: In JavaScript, a variable without a value, has the value undefined. The typeof is also undefined. In addition to these primitive data types, JavaScript supports a composite data type known as Object and Array. Object: JavaScript objects are written with curly braces. Object properties are written as name:value pairs, separated by commas. The object (person) in the example above has 3 properties: firstname, lastname and age. var person = firstname:"peter", lastname:"pan", age:25; Array: JavaScript arrays are written with square brackets. Array items are separated by commas. The following code declares (creates) an array called cars, containing three items (car names): var cars = ["Audi", "Skoda", "Maruti"]; Javascript Operators An operator is a symbol that is used to perform specific mathematical or logical operations. JavaScript language supports following type of operators. Arithmetic Operators Comparison Operators Logical Operators Bitwise Operators Assignment Operators Conditional (or ternary) Operators String Operators typeof Operators Arithmetic Operators Arithmetic operators are used to perform arithmetic between variables and/or values. There are following arithmetic operators supported by JavaScript language. Assume variable A holds 10 and variable B holds 20 then: 5 Dept: CE DWSL (3360705) Ravi G. Shrimali
Assignment Operators Assignment operators are used to assign values to JavaScript variables. There are following assignment operators supported by JavaScript language: Conditional Operator JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. This operator first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation. The conditional operator has this syntax: 6 Dept: CE DWSL (3360705) Ravi G. Shrimali
Comparison Operators Comparison operators are used in logical statements to determine equality or difference between variables or values. There are following comparison operators supported by JavaScript language. Assume variable A holds 10 and variable B holds 20 then: Logical Operators Logical operators are used to determine the logic between variables or values. There are following logical operators supported by JavaScript language. Assume variable A holds 10 and variable B holds 20 then: Bitwise Operators The Bit operators work on 32 bits numbers. Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a JavaScript number. There are following bitwise operators supported by JavaScript language. Assume variable A holds 2 and variable B holds 3 then: 7 Dept: CE DWSL (3360705) Ravi G. Shrimali
String Operators The + operator can also be used to concatenate (add) strings. To add two or more string variables together, use the + operator which is shown in below example. Data1 = "What a very "; Data2 = "nice day"; Ans = txt1 + txt2; The output of Ans will be: What a very nice day Adding two numbers, will return the sum, but adding a number and a string will return a string: y = "5" + 5; z= "Hello" + 5; The result of x, y, and z will be: 55 Hello5 8 Dept: CE DWSL (3360705) Ravi G. Shrimali
The typeof Operator The typeof is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand. The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or boolean value and returns true or false based on the evaluation. Here is the list of return values for the typeof Operator : Javascript Literals Literals are the way you represent values in JavaScript. In other word, we can say that these are fixed values that you literally provide in your application source, and are not variables. The below section describe the following types of literals. Integers Literals Integers can be expressed in decimal (base 10), hexadecimal (base 16), or octal (base 8) format. A decimal integer literal consists of a sequence of digits without a leading 0 (zero). Some examples of integers literals are: 123, -20, 12345 // Decimal (base 10) 7b, -14, 3039 // Hexadecimal (base 16) 173, -24, 30071 // Octal (base 8) Floating Point Literals A floating point literal can have the following parts: a decimal integer, a decimal point ("."), a fraction, an exponent, and a type suffix. A floating point literal must have at least one digit, plus either a decimal point or "e" (or "E"). Some examples of floating point literals are: 3.1415-3.1E12.1e12 2E-12 9 Dept: CE DWSL (3360705) Ravi G. Shrimali
Boolean Literals The Boolean type has two literal values: true and false. Object literals An object literal is zero or more pairs of comma separated list of property names and associated values, enclosed by a pair of curly braces. In JavaScript an object literal is declared as follows: 1. An object literal without properties: var userobject= 2. An object literal with a few properties: var student= FirstName:"Peter", LastName:"Parker", Age:24 ; String Literals A string literal is zero or more characters enclosed in double (") or single (') quotes. A string must be delimited by quotes of the same type. The following are examples of string literals: "Hello! How are you?" 'Good Morning' "1234" "I am Peter \n My Hobby is Cricket" Special Characters You can use the following special characters in JavaScript string literals: \b indicates a backspace. \f indicates a form feed. \n indicates a new line character. \r indicates a carriage return. \t indicates a tab character. Escaping Characters You can insert quotes inside of strings by preceding them by a backslash. This is known as escaping the quotes. The following is the example of escaping character literals: var Message="He read \"the book of javascript\" by Peter James."; document.write(message); The result of this would be He read "the book of javascript" by Peter James. 10 Dept: CE DWSL (3360705) Ravi G. Shrimali
JavaScript Array Array is used to store multiple values in a single variable. An array can hold many values under a single name, and you can access the values by referring to an index number. Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. The main difference between array and object are that arrays use numbered indexes whereas objects use named indexes. Creating an Array Syntax: var array-name = [item1, item2,...]; OR var array-name = new Array(item1, item2,...); //Creating an Array object The Array parameter is a list of strings or integers. When you specify a single numeric parameter with the Array constructor, you specify the initial length of the array. The maximum length allowed for an array is 4,294,967,295. var Games = [ "Chess", "Cricket", "Football" ]; //create an array by simply assigning values You can access an array element by referring its index number. Games[0] is the first element (Chess) Games[1] is the second element (Cricket) Games[2] is the third element (Football) Creating a multi-level (multidimensional) structure. var matrix = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]; To access the value from multi-level structure. matrix[1][1]); //it will gives a value "5" Array Properties: Here is a list of each property and their description. Property constructor index length prototype Description Returns a reference to the array function that created the object. The property represents the zero-based index of the match in the string Sets or returns the number of elements in an array Allows you to add properties and methods to an Array object Array Methods Here is a list of each method and its description. Method Description Syntax concat() Joins two or more arrays, and returns a copy of the joined array.concat(value1, arrays. value2,..., valuen); 11 Dept: CE DWSL (3360705) Ravi G. Shrimali
indexof() Search the array for an element and returns its position. array.indexof(searchele ment[, fromindex]); join() Joins all elements of an array into a string. array.join(separator); lastindexof() Search the array for an element, starting at the end, and returns its position. array.lastindexof(search Element[, fromindex]); pop() Removes the last element of an array, and returns that array.pop(); element. push() Adds new elements to the end of an array, and returns the new length. array.push(element1,..., elementn); reverse() Reverses the order of the elements in an array. array.reverse(); shift() Removes the first element of an array, and returns that element. array.shift(); slice() Selects a part of an array, and returns the new array. array.slice( begin [,end] ); sort() Sorts the elements of an array. array.sort( comparefunction ); splice() Adds/Removes elements from an array. array.splice(index, howmany, [element1][,..., elementn]); tostring() Converts an array to a string, and returns the result. array.tostring(); unshift() valueof() Adds new elements to the beginning of an array, and returns the new length. Returns the primitive value of an array. It returns an array as a string. array.unshift( element1,..., elementn ); array.valueof(); <html> <head> <title>the Array Method Example</title> var Games=["Cricket", "Chess", "Football", "TableTennis","WWE"]; document.write("<b>pop Method </b>" + Games.pop() + "</br>"); // Removes the last element ("WWE") from Games document.write("<b>final Result after using Pop method: </b>" + Games +"</br></br>"); document.write("<b>push Method </b>" + Games.push("WWE") + "</br>"); // Adds a new element("wwe") to Games document.write("<b>final Result after using Push method: </b>" + Games + "</br></br>"); document.write("<b>shift Method </b>" + Games.shift() + "</br>"); // Removes the first element "Cricket" from Games 12 Dept: CE DWSL (3360705) Ravi G. Shrimali
document.write("<b>final Result after using Shift method: </b>" + Games + "</br></br>"); document.write("<b>unshift Method </b>" + Games.unshift("KhoKho") + "</br>"); // Adds a new element "KhoKho" to Games document.write("<b>final Result after using Unshift method: </b>" + Games + "</br></br>"); </head> <body> </body> </html> Pop Method WWE Final Result after using Pop method: Cricket,Chess,Football,TableTennis Push Method 5 Final Result after using Push method: Cricket,Chess,Football,TableTennis,WWE Shift Method Cricket Final Result after using Shift method: Chess,Football,TableTennis,WWE Unshift Method 5 Final Result after using Unshift method: KhoKho,Chess,Football,TableTennis,WWE Javascript Functions A JavaScript function is a block of code designed to perform a particular task. This eliminates the need of writing same code again and again. This will help programmers to write modular code. You can divide your big Programme in a number of small and manageable functions. Like any other advance programming language, JavaScript also supports all the features necessary to write modular code using functions. Function Definition: Before we use a function we need to define that function. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. The basic syntax is shown here: 13 Dept: CE DWSL (3360705) Ravi G. Shrimali
Syntax: function functionname(parameter-list) Block of code or statements function PrintMessage() alert("hello! How are you?"); Calling a Function: To invoke a function somewhere later in the script, you would simple need to write the name of that function as follows: PrintMessage(); Function Parameters: In Function, you can pass different parameters while calling a function. These passed parameters can be captured inside the function and any manipulation can be done over those parameters. A function can take multiple parameters separated by comma. function MyIntro(Name, Hobby) alert("my Name is " + Name + ". My Hobby is " + Hobby); Now we can call this function as follows: MyIntro('Peter Parker', 'Cricket' ); The return Statement: A JavaScript function can have an optional return statement. This is required if you want to return a value from a function. This statement should be the last statement in a function. For example, if you want to pass two numbers in a function and then you can expect from the function to return their multiplication in your calling program which is described below: 14 Dept: CE DWSL (3360705) Ravi G. Shrimali
function Multiplication(Number1, Number2) var Total; Total=Number1*Number2; return Total; Now we can call this function as follows. It will display a popup box showing a result the multiplication of two numbers. var result; result=multiplication(25, 25); alert(result); JavaScript Control Statements The Control Structures within JavaScript allow the program flow to change within a unit of code or function. These statements can determine whether or not given statements are executed, as well as repeated execution of a block of code. Javascript supports conditional statements are used to perform different actions based on different conditions. In JavaScript we have the following conditional statements: if to specify a block of code to be executed, if a specified condition is true. If else to specify a block of code to be executed, if the same condition is false. If else if to specify a new condition to test, if the first condition is false. switch to specify many alternative blocks of code to be executed. The if Statement This statement is used to specify a block of JavaScript code to be executed if a condition is true. Syntax: if (condition or expression) Block of code to be executed if the condition is true The Following below example display a message if the age is greater than 18. 15 Dept: CE DWSL (3360705) Ravi G. Shrimali
var age=20; if (age>18) document.write("great you are eligible to apply for driving license"); Great you are eligible to apply for driving license The if else Statement This statement is used to specify a block of code to be executed if the condition is false. Syntax: if (condition or expression) Block of code to be executed if the condition is true else Block of code to be executed if the condition is false The Following below example display a message if the age is greater than 18 otherwise it will display a message that is written in the else portion. var age=15; if (age < 18) document.write("great you are eligible to apply for driving license"); else document.write("sorry you are not eligible to apply for driving license"); Sorry you are not eligible to apply for driving license The if else if Statement This statement is used to specify a new condition if the first condition is false. 16 Dept: CE DWSL (3360705) Ravi G. Shrimali
Syntax: if (condition1 or expression1) Block of code to be executed if condition1 is true else if (condition2 or expression2) Block of code to be executed if the condition1 is false and condition2 is true else Block of code to be executed if the condition1 is false and condition2 is false var book="history"; if(book=="history") document.write("<b>you Select History Book</b>"); else if(book=="maths") document.write("<b>you Select Maths Book</b>"); else if(book=="economics") document.write("<b>you Select Economics Book</b>"); else document.write("<b>you Select nothing</b>"); You Select History Book The Switch Statement This statement is used to select one of many blocks of code to be executed. The switch expression is evaluated once. The value of the expression is compared with the values of each case. If there is a match, the associated block of code is executed. 17 Dept: CE DWSL (3360705) Ravi G. Shrimali
When the JavaScript code interpreter reaches a break keyword, it breaks out of the switch block. This will stop the execution of more execution of code and/or case testing inside the block. Syntax: switch(expression) case condition 1: statement(s) break; case condition 2: statement(s) break;... case condition n: statement(s) break; default: statement(s) var grade=2; document.write("you got "); switch (grade) case 1: document.write("distinction.<br />"); break; case 2: document.write("first Class.<br />"); break; case 3: document.write("second Class.<br />"); break; case 4: document.write("pass Class.<br />"); break; default: document.write("fail.<br />"); You got First Class. Looping Structure While writing a program, there may be a situation when you need to perform some action over and over again. In such situation you would need to write loop statements to reduce the number of lines. JavaScript supports all the necessary loops: for, for...in, while and do...while. 18 Dept: CE DWSL (3360705) Ravi G. Shrimali
The for Loop The for loop is the most compact form of looping and includes the following three important parts: The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins. The test statement which will test if the given condition is true or not. If condition is true then code given inside the loop will be executed otherwise loop will come out. The iteration statement where you can increase or decrease your counter. You can put all the three parts in a single line separated by a semicolon. Syntax: for(initialization; test condition; iteration statement) Block of code to be executed if test condition is true var count; document.write("print the numbers from 1 to 5" + "<br />"); for(count=1; count<=5; count++) document.write("current Count: " + count ); document.write("<br />"); document.write("finally Print!"); Print the numbers from 1 to 5 Current Count: 1 Current Count: 2 Current Count: 3 Current Count: 4 Current Count: 5 Finally Print! The while Loop The main purpose of using a while loop is to execute a statement or code block repeatedly as long as expression is true. Once expression becomes false, the loop will be exited. Syntax: while(expression) Block of code to be executed 19 Dept: CE DWSL (3360705) Ravi G. Shrimali
var count=1; document.write("print the numbers from 1 to 4" + "<br />"); while(count<5) document.write("current Count: " + count); document.write("<br />"); count++; document.write("finally Print!"); Print the numbers from 1 to 4 Current Count: 1 Current Count: 2 Current Count: 3 Current Count: 4 Finally Print! The do...while Loop The do...while loop is works similar like to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false. Syntax: do Block of code to be executed; while(expression); var count=1; document.write("starting Loop" + "<br />"); do document.write("current Count: " + count + "<br />"); count++; while(count < 2); document.write("loop stopped!"); 20 Dept: CE DWSL (3360705) Ravi G. Shrimali
Starting Loop Current Count: 1 Loop stopped! The for...in Loop There is one more loop supported by JavaScript. It is called for...in loop. This loop is used to loop through an object's properties. In each iteration one property from object is assigned to variablename and this loop continues till all the properties of the object are exhausted. Syntax: for (variablename in object) Statement or block to execute var message=""; var person=firstname:"peter", LastName:"Parker", Age:20; var addvalue; document.write("<b>information of an Employee:</b><br/> "); for(addvalue in person) document.write(person[addvalue]); document.write("<br />"); document.write("thanks for the Details!"); Information of an Employee: Peter Parker 20 Thanks for the Details! JavaScript Loop Control JavaScript provides you full control to handle your loops and switch statement. There may be a situation when you need to come out of a loop without reaching at its bottom. There may also be a situation when you want to skip a part of your code block and want to start next iteration of the look. 21 Dept: CE DWSL (3360705) Ravi G. Shrimali
To handle all such situations, JavaScript provides break and continue statements. These statements are used to immediately come out of any loop or to start the next iteration of any loop respectively. The break Statement The break statement is used to jump out of a loop. The break statement will stop the execution of code and/or case testing inside switch statement and continues executing the code after the loop. <html> <head> <title>the Break Statement</title> function breakloop() var count = 0; document.write("entering the loop<br/>"); while(count < 20) if (count==5) break; // breaks out of loop completely count=count+1; document.write(count + "<br />"); document.write("exiting the loop!<br/>"); </head> <body> <p>click the button to see the result using Break Statement.</p> <button onclick="breakloop();">try it</button> </body> </html> The above code will produce the below result when button is pressed. Entering the loop 1 2 3 22 Dept: CE DWSL (3360705) Ravi G. Shrimali
4 5 Exiting the loop! The Continue Statement The continue statement tells the interpreter to immediately start the next iteration of the loop and skip remaining code block. When a continue statement is encountered, program flow will move to the loop check expression immediately and if condition remain true then it start next iteration otherwise control comes out of the loop. <html> <head> <title>the Continue Statement</title> function continueloop() var count = 0; document.write("entering the loop<br/>"); while(count < 10) count=count+1; if (count==5) continue; // skill rest of the loop body document.write(count + "<br />"); document.write("exiting the loop!<br/>"); </head> <body> <p>click the button to see the result using Continue Statement.</p> <button onclick="continueloop();">try it</button> </body> </html> The above code will produce the below result when button is pressed. 23 Dept: CE DWSL (3360705) Ravi G. Shrimali
Entering the loop 1 2 3 4 6 7 8 9 10 Exiting the loop! Using Labels to Control the Flow A label is simply an identifier followed by a colon that is applied to a statement or block of code. We will see two different examples to understand label with break and continue. A label can be used with break and continue to control the flow more precisely. <html> <head> <title>using Labels to Control the Flow</title> function Labeldemo() document.write("entering the loop!<br /> "); outerloop: // This is the label name for(var i=0;i<3; i++) document.write("outerloop: " + i + "<br />"); innerloop: for(var j=0;j<5;j++) if(j > 2) break innerloop; // Quit the innermost loop document.write("innerloop: " + j + " <br />"); 24 Dept: CE DWSL (3360705) Ravi G. Shrimali
document.write("exiting the loop!<br /> "); </head> <body> <p>click the button to see the result using Labels.</p> <button onclick="labeldemo();">try it</button> </body> </html> The above code will produce the below result when button is pressed. Entering the loop! Outerloop: 0 Innerloop: 0 Innerloop: 1 Innerloop: 2 Outerloop: 1 Innerloop: 0 Innerloop: 1 Innerloop: 2 Outerloop: 2 Innerloop: 0 Innerloop: 1 Innerloop: 2 Exiting the loop! 25 Dept: CE DWSL (3360705) Ravi G. Shrimali