Docstoc

Introduction to Javascript (DOC)

Document Sample
Introduction to Javascript (DOC) Powered By Docstoc
					                                              Javascrip


What is JavaScript?

         JavaScript was designed to add interactivity to HTML pages
         JavaScript is a scripting language
         A scripting language is a lightweight programming language
         JavaScript is usually embedded directly into HTML pages
         JavaScript is an interpreted language (means that scripts execute without preliminary
          compilation)
         Everyone can use JavaScript without purchasing a license

Are Java and JavaScript the same?

NO!

Java and JavaScript are two completely different languages in both concept and design!

What can a JavaScript do?

          Programming tool - HTML authors are normally not programmers, but JavaScript is a
          scripting language with a very simple syntax.
         JavaScript can put dynamic text into an HTML page - A JavaScript statement like this:
          document. write("<h1>" + name + "</h1>") can write a variable text into an HTML page
         Popup windows- JavaScript can be used to create popup windows. These windows are
          normally used to display important announcements, offers and news etc.
         JavaScript can read and write HTML elements - A JavaScript can read and change the
          content of an HTML element
         Input Validation - A JavaScript can be used to validate form data before it is submitted to a
          server. This saves the server from extra processing. For example, if the user enters his email
          address, it must be a valid email. JavaScript code can ensure the validity by checking that is
          contains @ symbol and dot(.).
         JavaScript can be used to create cookies(a piece of information) - A JavaScript can
          be used to store and retrieve information on the visitor's computer

JavaScript is Case Sensitive:

Unlike HTML, JavaScript is case sensitive - therefore watch your capitalization closely when you write
JavaScript statements, create or call variables, objects and functions .

JavaScript Statements:


Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                                        Page 1
A JavaScript statement is a command to a browser. The purpose of the command is to tell the browser
what to do. This JavaScript statement tells the browser to write "Hello World" to the web page:

document. write(“hello world”);

Note: Using semicolons makes it possible to write multiple statements on one line .

JavaScript Code:

JavaScript code (or just JavaScript) is a sequence of JavaScript statements.Each statement is executed
by the browser in the sequence they are written.

This example will write a heading and two paragraphs to a web page:

Example

<script language=”javascript">

document. write("<h1>This is a heading</h1>");

document. write("<p>This is a paragraph.</p>");

document. write("<p>This is another paragraph.</p>");

</script>

Data Types:

Javascript provides the following data types.

       Numeric Data: Numeric data consists of numbers. it may be whole numbers and real
        number. Numeric data may be consist of the following. Numeric data is further divided in
        two types.

                    1. Integer:

                        Integers can be represented in decimal, hexadecimal and octal form.

                                  Decimal: These are from 0 to 9.

                                  Hexadecimal: These are from 0 to 15.the numbers from 10 to 15 are
                                  represented by letters A to F.

                                  Octal: octal numbers are from 0 to 7.

Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                                      Page 2
                      2. Floating point numbers:

                           These values require decimal points such as 34,45 or exponential notation such
                           as 3F4 etc. These can be positive and negative.

        Logical or Boolean:

         This data type includes true and false. This is normally used to indicate a condition.




        String:

         It includes all values which we write in single or double quotes. For example
         “Pakistan”,”cricket”,”99”.

JavaScript Variables:

 JavaScript variables are used to hold values or expressions. A variable can have a short name, like x, or a more
descriptive name, like Pakistan,world.. Rules for JavaScript variable names:

        Variable names are case sensitive (y and Y are two different variables)
        Variable names must begin with a letter or the underscore character
        Reserved words are not allowed.
        Special characters cannot be variable name.
        Blank spaces are not allowed.
        Both Upper and Lower case are allowed.

Note: Because JavaScript is case-sensitive, variable names are case-sensitive.

Declaring (Creating) JavaScript Variables:

Creating variables in JavaScript is most often referred to as "declaring" variables.You declare JavaScript
variables with the var keyword:

         Var a;

         Var hello;

After the declaration shown above, the variables are empty (they have no values yet). However, you can
also assign values to the variables when you declare them:

var x=10;;

Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                                                   Page 3
var abc=”hello”;

After the execution of the statements above, the variable x will hold the value 10, and abc will hold the
value hello. Note: When you assign a text value to a variable, use quotes around the value.

Literals(constant):

        Constants can be used to represent values in javascript. Constants are fixed values that cannot
        be changed during the execution of the code .javascript provides different types of literals.

                     1. Floating point constants
                     2. Integer constants
                     3. String constants




JavaScript Comments:

JavaScript comments can be used to make the code more readable.

JavaScript Comments

Comments can be added to explain the JavaScript, or to make the code more readable.

Single line comments start with //.

The following example uses single line comments to explain the code:

Example:      <script language="javascript">

// Write a heading

document.write("<h1>This is a heading</h1>");

// Write two paragraphs:

document.write("<p>This is a paragraph.</p>");

document.write("<p>This is another paragraph.</p>");

</script>

JavaScript Multi-Line Comments:
Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                                          Page 4
Multi line comments start with /* and end with */. The following example uses a multi line comment to explain the
code: Example:

<script language="javascript">

/*

The code below will write

one heading and two paragraphs

*/

document. write("<h1>This is a heading</h1>");

document. write("<p>This is a paragraph.</p>");

document. write("<p>This is another paragraph.</p>");

</script>




JavaScript Operators:
An operator is a symbol that performs some operations. The value on which the operator performs
operation is called operands. There is two categories of operators.

                  Binary operator: A type of operator which works with two operands is known as binary
                   operator.

                  Unary operator: A type of operator which works with one operand is known as unary
                   operator.

Some important types of operators in javascript are as follows:

     1.     Assignment Operator:( = is used to assign values)

         An assignment operator is used to assign the values to the variables. A statement that assigns a value to a
variable is called an Assignment statement. An assignment that assigns a value to many variables is known as
compound assignment statement.

     2. Arithmetic Operators:


             Arithmetic operators are used to perform arithmetic between variables and/or values. The

Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                                                    Page 5
Standard arithmetic operators are addition(+),subtraction(_),multiplication(*) and division(/).

Operators      Description                                                              Examples


+             It is a binary operator. it adds two numbers and returns the result.      5+2 returns 7.


-             It is a binary operator. it subtracts two numbers and returns the         7-2 returns 5.

              result.

*             It is a binary operator. it multiplies two numbers and returns the        7*2 returns 14.

              result.

/             It is a binary operator. it divides left operand by right operand and     10/2 returns 5.

              returns the result.

%             Modulus operator is a binary operator and returns integer                 13%5 returns 3.

              remainder of dividing the two operands.

++            It is a unary operator. It add 1 to operand.                              If x is 3, then ++x is
                                                                                        used. it will return 4
                                                                                        to x.




The + Operator Used on Strings:

The + operator can also be used to add string variables or text values together . To add two or more string
variables together, use the + operator.

         txt1="Pakistan will";


         txt2="win the world cup";


         txt3=txt1+txt2;


After the execution of the statements above, the variable txt3 contains "Pakistan will win the world cup".

To add a space between the two strings, insert a space into one of the strings:

txt1="Weather is       ";

txt2="very pleasant today";


Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                                                      Page 6
txt3=txt1+txt2;

After the execution of the statements above, the variable txt3 contains "Weather is      very pleasent".




Or you can insert a space into the expression:

txt1="What a very";

txt2="nice day";

txt3=txt1+" "+txt2;

After the execution of the statements above, the variable txt3 contains: "What a very    nice day".




     3.   Comparison Operators:
                    Comparison and Logical operators are used to test for true or false. Comparison operators are
          used in logical statements to determine equality or difference between variables or values. Given that x=5,
          the table below explains the comparison operators:

Operator           Description                                          Example

==                 is equal to                                          x==8 is false



!=                 is not equal                                         x!=8 is true


>                  is greater than                                      x>8 is false


<                  is less than                                         x<8 is true


>=                 is greater than or equal to                          x>=8 is false


<=                 is less than or equal to                             x<=8 is true



How to use comparison operators?
Comparison operators can be used in conditional statements to compare values and take action depending on the
result:
if (age<18)
document.write("Too young");




Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                                                    Page 7
     4. Logical Operators:

Logical operators are used to determine the logic between variables or values. Given that x=6 and y=3, the table
below explains the logical operators:

Operators                         Description                              Example

&&                                and                                      (x < 10 && y > 1) is true


||                                or                                       (x==5 || y==5) is false


!                                 not                                      !(x==y) is true




Operators Precedence:

Operator precedence determines the order in which operators are evaluated. Operators with higher precedence are
evaluated first. A common example:

Each operator has its own precedence level. If an expression contains different types of operators, the operator with
higher precedence is evaluated before the operators with lower precedence. The order of precedence in JavaScript is
as follow:

        Any expression given in parentheses is evaluated first.

        Then multiplication (*) and division(/) operator are evaluated.

        Then plus (+) and minus (-) operators are evaluated.

        In case of parentheses within parentheses, the expression of the inner parentheses will be evaluated first.

Operators Associativity:
The order in which operators of same precedence are evaluated is known as operators associativity. If an expression
contains some operators that have same precedence level, the expression is evaluated either from left-to right or
right-to-left.



Example:

 The expression 10 * 24 / 5 -2 +13 contains four operators. Two operators * and / have equal precedence. These
expressions will be evaluated from left-to-right. Similarly, two operators + and _ also have equal precedence. So the
expression will be evaluated in the following order:

                           10 * 24 / 5 – 2 +13




Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                                                    Page 8
                                      240 / 5 – 2 +13



                                        48 – 2 + 13



                                         46 + 13



                                            59


JavaScript Conditional Statements:
Conditional statements are used to perform different actions based on different conditions. A statement or set of
statements that is executes when a particular condition is true and ignored when the condition is false is called
conditional statements. Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this. In JavaScript we have the following conditional
statements:

          if statement - use this statement to execute some code only if a specified condition is true
          if...else statement - use this statement to execute some code if the condition is true and another code if the
           condition is false
          if...else if....else statement - use this statement to select one of many blocks of code to be executed
          switch statement - use this statement to select one of many blocks of code to be executed

If Statement:

If statement is a decision making statement. It is used to execute or skip a statement or a set of statements by
checking a condition. The condition is given in relational expressions. If the condition is true, the statement or set of
statements after If Statement is executed. If the condition is false, the statement or set of statements after if
statement is not executed.

Syntax:
if (condition)

 {

 code to be executed if condition is true

 } (Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a JavaScript error!)

Example:

<html>


Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                                                         Page 9
          <body>

                   <script language="javascript">

                             var num;

                             num=prompt("enter a number","1");

                             if(num>=40)

                             document.write("you have passed");

                   </script>

          </body>

</html>

If...else Statement:
If else is another type of if statement. It executes one block of statement(s) when the condition is true and other when it is
false. In any situation, one block is executes and other is skipped. In if else statement, both blocks of statement can never
be executed and both blocks of statements can never be skipped.

Syntax:
if (condition)

 {

Statement(s);

 }

else

 {

 Statement(s);

 }



Multiple conditions in if...else:

Use the if....else if...else statement to select one of several blocks of code to be executed.

Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                                                           Page 10
Syntax:
if (condition1)

 {

 code to be executed if condition1 is true

 }

else if (condition2)

 {

 code to be executed if condition2 is true

 }

else

 {

 code to be executed if condition1 and condition2 are not true

 }

Example:

<html>

<body>

           <script language="javascript">

           var marks;

           marks=prompt("enter your marks");

           if(marks>=80)

                   document.write("Grade:A");

           else if(marks>=60)

                   document.write("Grade:B");

           else if(marks>=40)

                   document.write("Grade:C");

           else

                   document.write("Grade F");


Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                      Page 11
          </script>

</body>

</html>

Nested “If” Statement:

          An if statement within an if statement is called nested if statement. In nested structure, the control enters
into the inner if only when the only outer condition is true.

Syntax:

                                     if(condition)

                                               if(condition)

                                               {

                      Inner if                                    statement(s);

Outer if                                                }

                                               else

                                               {

                                                        statement(s);

                                               }

                                     else

                                     {

                                     statement(s);

                             }

Switch Statement:
The switch statement is another conditional structure. It is a good alternative of nested if-else. It can be
easily used when there are many choices available and only one should be executed.

Syntax:

          switch(n)

Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                                                      Page 12
{

case 1:

           execute code block 1

           break;

case 2:

           execute code block 2

           break;

default:

    code to be executed if n is different from case 1 and 2

}

This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value
of the expression is then compared with the values for each case in the structure. If there is a match, the block of
code associated with that case is executed. Use break to prevent the code from running into the next case
automatically.

Loops:
A statement or set of statements that is executed repeatedly is known as loop. The structure that repeats
a statement(s) is known as iterative,repetitive or looping structure. Loops are basically used for two
purposes.

          To execute a statement or number of statements for a specified number of times. For example, a
           user may displayhis name on screen for 10 times.

          To use a sequence of values. For example, a user may display a set of natural numbers from 1 to
           10.

      Javascript provide three types of loops.

              While loop

              Do-while loop

              For loop

      1.   While loop:

Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                                                 Page 13
While loop is the simplest loop in javascript. This loop executes one or more statements while the given
condition remains true.

Syntax:

While(condition)

          Statement;

The syntax for compound statements is as follow:

While(condition){

          Statement 1;

          Statement 2;

Statement 3;

:

Statement N;

}

Example:

<html>

          <body>

                   <script language=”javascript”>

                   Var n,I;

                   N=prompt(“enter a number”);

                   I=1;

                   While(i<=n){

                   document.write(i+”<br>”);

                   i=i+1;

                   }

                   </script>


Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                                       Page 14
          </body>

</html>

   2. do while Loop:

   The do...while loop is a variant of the while loop. do-while is similar to while loop. The only
   difference is that the condition is checked after executing the body of the loop. The condition
   comes after the body of the loop. It means that the body of do-while executes at least once.
   Syntax:

   do

     {

     code to be executed

     }

   while (condtion);

   Example:

   <html>

          <body>

                <script language="javascript">

                var i=0;

                do

                {

                           document.write("The number is " + i);

                           document.write("<br />");

                        i++;

                    }

                        while (i<=5);

                </script>

Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                                 Page 15
       </body>

   </html>

   The above example uses a do...while loop. The do...while loop will always be executed at
   least once, even if the condition is false, because the statements are executed before the
   condition is tested:

   3. for Loop:

       for loop executes one or more statements for a specified number of times. This loop is
       also called counter-controlled loop. When the JavaScript interpreter comes across a
       for loop, it executes the initialization statements and then checks the condition. Only
       when the condition returns 'true', the interpreter enters the loop. After the first iteration,
       the updation statements are executed and then the condition is evaluated again. This
       continues till the condition returns 'false' and the loop stops.

       Some important points to note are:

      The initialization statements are executed once; only when the for loop is encountered.

      After execution of initialization statements, the condition is evaluated.

      After every iteration, the updation statements are executed and then the condition is
       checked.



       Syntax:

       For(initialization;condition;increment/decrement)

       {

               Statement 1;

               Statement 2;

               Statement 3;

       }

       Example:



Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                                    Page 16
       <html>
       <body>
       <script language=”javascript">
       var i=0;
       for (i=0;i<=5;i++)
       {
       document.write("The number is " + i);
       document.write("<br />");
       }
       </script>
       </body>
       </html>

       Nested Loop:

       A loop within a loop is called nested loop. In nested loops,the inner loop is executed
       completely with each change in the value of counter variable of outer loop.

       Systax:

                               for(initialization;condition;increment/decrement)

       outer

       loop                    {

                                       for(initialization;condition;increment/decrement)

                       inner loop              {

                                               Statement(s);

                                       }

                               }

       Functions and Arrays:
       A function is a named block of code that performs. A function contains code that will be executed
       by an event or by a call to the function. You may call a function from anywhere within a page.
       Functions can be defined both in the <head> and in the <body> section of a document.
       However, to assure that a function is read/loaded by the browser before it is called, it could be
       wise to put functions in the <head> section.


       How to Define a Function?

Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                                     Page 17
       Syntax:
       function functionname(var1,var2,...,varX)
       {
       some code
       }

       The parameters var1, var2, etc. are variables or values passed into the function. The { and the }
       defines the start and end of the function.

       Note: A function with no parameters must include the parentheses () after the function name.

       Note: Do not forget about the importance of capitals in JavaScript! The word function must be
       written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a
       function with the exact same capitals as in the function name.

       Function Call:

       The statements that activates a funtion is called as function call. A function is called with
       its name. Function name is followed by necessary parameter in parentheses. If there are
       many parameters, You must separate them by placing comma between them. If there is
       no parameter then use empty parentheses. When any function is called, The following
       steps take place.

               The control moves to the function when it is called.

               All statements in the function body are executed.

               The control returns back to the calling function.

       Example:

       <html>

                <head>

                       <script language=”javascript”>

                       Function fun1()

                       {

                                Document.write(“creating function is really intresting”);

                       }

Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                                        Page 18
                       </script>

                </head>

       <body>

                <script language=”javascript”>

                       document.write(“lets call a funtion”);

                       fun1();

                       document.write(“we called a function”);

                </script>

       </body>

       Passing parameters to Functions:

       Parameters are the values that are provided toafunction when thefunctionis called.
       Parameters are given in the parentheses. If thee are many parameters, these are
       seperated by commas. If there is no parameter, empty parentheses are used. The
       number of parameters in function call must be the same to the number of parameters in
       function declaration.

               Parameters in function call are called actual parameters/variables.

               Parameters in function declaration are called formal parameters/variables

       Example:

       <html>

                <head>

                       <script language=”javascript”>

                       Function num(a){

                                 document.write(a*a);

                                 }

                       </script>

Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                            Page 19
               </head>

       <body>

               <script language=”javascript”>

               var n;

               n=prompt(“enter a number”);

               num(n);

               </script>

       </body>

       </html>

Returning a Value:

         A function can return a single value. The return statement is used to specify the value
that is returned from the function.

So, functions that are going to return a value must use the return statement. One more thing a
function can do is return a value. Suppose we have the following function:

function calculate(a,b,c) {

       d = (a+b) * c;

       return d;

}

This function calculates a number from the numbers you pass to it. When it's done it returns the
result of the calculation.

The Lifetime of JavaScript Variables:
If you declare a variable, using "var", within a function, the variable can only be accessed within
that function. When you exit the function, the variable is destroyed. These variables are called
local variables. You can have local variables with the same name in different functions, because
each is recognized only by the function in which it is declared.



Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                                Page 20
If you declare a variable outside a function, all the functions on your page can access it. The
lifetime of these variables starts when they are declared, and ends when the page is closed.

Built-in functions:
JavaScript has a number of built-in functions. A type of function that is provided by javascript is
called built-in functions. Javascript provides many built-in functions to write scripts easily and
speedily.

Dialog Boxes:

JavaScript supports three important types of dialog boxes. These dialog boxes can be used to
raise and alert, or to get confirmation on any input or to have a kind of input from the users

     1. Alert Dialog Box:

         An alert dialog box is mostly used to give a warning message to the users. Like if one
         input field requires to enter some text but user does not enter that field then as a part
         of validation you can use alert box to give warning message as follows:

         <head>

         <script language="javascript">




           alert("Warning Message");




         </script>

         </head>

         Alert box gives only one button "OK" to select and proceed.

     2. Confirmation Dialog Box:

              A confirmation dialog box is mostly used to take user's consent on any option. It
       displays a dialog box with two buttons: OK and Cancel. If the user clicks on OK button
       the window method confirm() will return true. If the user clicks on the Cancel button
       confirm() returns false. You can use confirmation dialog box as follows:


Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                                 Page 21
                 <html>

                          <body>

                                 <script language=”javascript”>

                                 Var r;

                                 r=confirm(“click any button”);

                                 if(r==true)

                                          document.write(“you clicked ok”);

                                 else

                                          document.write(“you clicked cancel”);

                                 </script>

                          </body>

                 </html>


     3.     Prompt Dialog Box:
     The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus it
     enable you to interact with the user. The user needs to fill in the field and then click OK. This dialog
     box is displayed using a method called prompt() which takes two parameters.

     (i)       A label which you want to display in the text box.
     (ii)      A default string to display in the text box. This dialog box with two buttons: OK and Cancel.
               If the user clicks on OK button the window method prompt() will return entered value from
               the text box. If the user clicks on the Cancel button the window method prompt() returns
               null

     Array:

                 An array is a collection of consecutive memory locations. Each memory location
                 is called an element of array. The number of elements in an array is called the
                 length of an array. All elements have one collective name. The Array object is
                 used to store multiple values in a single variable. An array is a special variable,
                 which can hold more than one value, at a time.



Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                                         Page 22
               The following points should always be remembered when using arrays in
               JavaScript:

                     The array is a special type of variable.
                     Values are stored into an array by using the array name and by stating
                      the location in the array you wish to store the value in brackets. Example:
                      myArray[2] = "Hello World";
                     Values in an array are accessed by the array name and location of the
                      value. Example: myArray[2];

Creating a JavaScript Array:
       Creating an array is slightly different from creating a normal variable. Because
JavaScript has variables and properties associated with arrays. This example shows how you
would create a simple array, store values to it, and access these values.

       var myArray = new Array();

       myArray[0] = "Football";

       myArray[1] = "Baseball";

       myArray[2] = "Cricket";

       document.write(myArray[0] + myArray[1] + myArray[2]);




                               .




Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                                                                              Page 23
Prepared by:

Aisha Rafiq (coordinator CS)

ITM College                    Page 24

				
DOCUMENT INFO
Shared By:
Stats:
views:17
posted:6/8/2012
language:English
pages:24