Tuesday, October 21, 2014

IF condition statement in javascript , Switch case statement in javascript

  • CONDITIONAL STATEMENTS:
  • Conditional statements in JavaScript are used to perform different actions based on different conditions.
  • 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 if you want to execute some code    

                       only if a specified condition is true

  • if...else statement - use this statement if you want 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 if you want to select

                                             one of many blocks of code to be executed

  • switch statement - use this statement if you want to select one of

                               many blocks of code to be executed

IF STATEMENT:

  • You should use if statement if you want to execute some code only if a specified condition is true.

Syntax:
        If <condition>
{
JavaScript code executed if condition becomes true.
}

Example:
<script language = "javascript">
var x = 5,y=6;
if (x>y)
{
document.write(' x is greater');
}
</script>

IF...ELSE STATEMENT:

  • If you want to execute some code if a condition is true and another code if the condition is not true, use if....else statement.

Syntax:

            if (condition) 
            { 
Code to be executed if condition is true 
            } 
            else 
            { 
Code to be executed if condition is not true
            } 

 

Example:
<script language = "javascript">
x = 5;
y = 6;
if (x > y)
{
document.write('x is greater');
}
else
{
document.write('y is greater');
}
</script>

IF…ELSE IF…ELSE STATEMENT:
  • It is used when user have two or more condition to check for execution of code.

Syntax:
          if <condition1>
{
          Code if condition 1 is true;
}
else if <condition2>
{
          Code if condition 2 is true;
}
else
{
          Code if no condition becomes true;
}

Example:
            <script language = "javascript">
                        x=5;
     y=6;
     z=7;
     if(x>y && x>z)
     {
                 document.write('x is greater');
     }
     else if(y>x && y>z)
     {
                 document.write('y is greater');
     }
     else
     {
                 document.write('z is greater');
     }
            </script>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


SWITCH STATEMENT:

  • use the switch statement to select one of many blocks of code to be executed

 

Syntax:
        switch (n)

          { 
    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
           } 
 


  • 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.

Operators In Javascript

  • JAVASCRIPT OPERATOR:

ARITHMATIC OPERATOR
ASSIGNMENT OPERATOR
COMPARISION OPERTOR
LOGICAL OPERATOR
CONDITIONAL OPERATOR

ARITHMATIC OPERATOR:

  • Arithmetic operators are used to perform arithmetic between variables

and/or values.

  • Given that y=5, the table below explains the arithmetic operators:

Operator

Description

Example

Result

+

Addition

x=y+2

x=7

-

Subtraction

x=y-2

x=3

*

Multiplication

x=y*2

x=10

/

Division

x=y/2

x=2.5

%

Modulus (division remainder)

x=y%2

x=1

++

Increment

x=++y

x=6

--

Decrement

x=--y

x=4

 

 

 

 

ASSIGNMENT OPERATOR:

  • Assignment operators are used to assign values to JavaScript variables.
  • Given that x=10 and y=5, the table below explains the assignment operators:

Operator

Example

Same As

Result

=

x=y

 

x=5

+=

x+=y

x=x+y

x=15

-=

x-=y

x=x-y

x=5

*=

x*=y

x=x*y

x=50

/=

x/=y

x=x/y

x=2

%=

x%=y

x=x%y

x=0

 

 

 

 

 

COMPARISION OPERATOR:

  • 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 exactly equal to (value and  type)

x===5 is true
x==="5" 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 Can it be Used

  • Comparison operators can be used in conditional statements to compare values and take action depending on the result:

 For Example:

    If (age<18) 
               document.write("Too young");
 LOGICAL OPERATOR:
  • 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:

Operator

Description

Example

&&

        and

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

||

          or

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

!

          not

!(x==y) is true

 

 

 

 CONDITIONAL OPERATORS:

  • JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

Syntax:
<Variable name> = <condition>? value1: value2

    Example:
x = (y == 5)? “x is true”:”x is false”
- Here if value of y is 5 then value of x = “x is true”
- If value of y is not 5 then value of = “x is false”


Basics Of Array In Javascript

Array In JavaScript:

  • An array is a special variable, which can hold more than one value, at a time.
  • Each element in the array has its own ID so that it can be easily accessed.
  • It is important to realize that each value is stored in one element of the array and
  • These elements start at 0.

Types Of JavaScript:
1)Basic Array :
        - Basic Array represent one or value separated by commas. 
- The value can be a mixtures of a string, numbers and variables.
- Each array item gets an index number associated with it`s key.
Build a basic array and access its item directly by their index number.
var choice=[“RED”,”Cricket”,”Kal Ho Na Ho”];
document.write(choice[0]+”Is my Favourite Color.<br/>”);
document.write(choice[1]+”Is my Favourite Game.<br/>”);
document.write(choice[2]+”Is my Favourite Movie.<br/>”);

Populate array by placing value directly into  index position of the array.
var game=[];
game[0]=”Cricket”;
game[1]=”Football”;
game[2]=”Chess”;
document.write(game);
                  

2)Associative Array :
        - Associative array give you a way to label your array item key.
- The key is directly associated to its value in a meaningful way.
- Example:

                var arr={name:”KALPESH”, surname=”RAKHOLIYA”,age=22};
document.write(arr[“name”]+”And Surname Is:”+arr[“surname”]+”<br>”);
document.write(arr[“name”]+”And Age Is:”+arr[“age”]+”<br>”);

3)Multidimensional Array :
        - Multidimensional array is an array that holding multiple array that can be of various types.
- Example:
var arr=new Array
(
[“Sachin”,”Sehwag”,”Kohli”],
[“Watson”,”Warner”,”Hussy”],
[“Cook”,”Campton”,”Piterson”]
);
document.write(arr[0]+”<br>”);
document.write(arr[1]+”<br>”);
document.write(arr[2]+”<br>”);


Datatype Conversion

Types Conversion Function:

1)isNan():Check to see if what is passed is not a number,return a boolean output

<script type="text/javascript">
document.write("111 IS:"+isNaN(111)+"<br>");
document.write("-111.45 IS:"+isNaN(-111.45)+"<br>");
document.write("Hello IS:"+isNaN("Hello")+"<br>");
</script>

2)eval():It convert String to Integer or Float
It Can Also Evalute the Expression include with a string.

<script type="text/javascript">
var Ans=eval("256/7*8");
document.write("The Correct Answer IS:"+Ans);
</script>

3)parseInt():Convert The String to Integer Value.
Return The First Integer Which is Contain in String.

<script type="text/javascript">
document.write("111.111 Value:"+parseInt(111.111)+"<br>");
document.write("123Good456 Value:"+ parseInt (123Good456)+"<br>");
document.write("Hello Value:"+ parseInt ("Hello")+"<br>");
</script>

4)parseFloat():Convert The String to Floating Point Number.
Return The First Floating Point Number  Which is Contain in String.

<script type="text/javascript">
document.write("111.111 Value:"+parseFloat(111.111)+"<br>");
document.write("123.45Good1 Value:"+ parseFloat(123.45Good1)+"<br>");
document.write("Hello Value:"+ parseFloat ("Hello")+"<br>");
</script>


javascript variable scope and datatypes

JAVASCRIPT VARIABLES:
- Variable is container for storing the information.
- Variable names are case sensitive. (x and X are two different variable).
- Variable names must be started with letter or underscore.
- To declare variable in JavaScript var statement is used.
- Syntax: VAR <variable name>
NOTE: it is not compulsory to declare variable in JavaScript before its use.
- If you assign values to variables that have not yet been declared, the variables will  
  automatically be declared.

 <html><body>
<script language = "JavaScript">
var x = 10; < - - - - - variable x is declared.
var y = 20; < - - - - - variable y is declared.
z = x+y;      < - - - - - variable z is not declared.
document.write('addition is' + z);
</script>
</body>
</html> (semicolon in JavaScript is optional)

Scope/Life-Time of variable in JavaScript:
- A variable declared within a JavaScript function becomes LOCAL and can only be  
accessed within that function. (The variable has local scope).
- You can have local variables with the same name in different functions, because local
variables are only recognized by the function in which they are declared.
- Local variables are destroyed when you exit the function.
- Variables declared outside a function become GLOBAL, and all scripts and functions
on the web page can access it.
- Global variables are destroyed when you close the page.
- If you declare a variable, without using "var", the variable always becomes GLOBAL.

Data Types in Java Script:
1)Number:Integer Number,Float Number,NaN
2)String:it include charachter and words
3)Boolean:return TRUE or FALSE


Javascript Blocks and Comments

JavaScript Blocks:

- JavaScript statements can be grouped together in blocks.
- Blocks start with a left curly bracket {, and ends with a right curly bracket }.
- The purpose of a block is to make the sequence of statements execute together.
<script type="text/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>
- Normally a block is used to group statements together in a function or in a condition   
(where a group of statements should be executed if a condition is met).

Comments in JavaScript:
- JavaScript comments can be used to make the code more readable.
- Comments can be added to explain the JavaScript, or to make the code more readable.
1)Single line comments start with //.
2)Multi line comments start with /* and end with */.
3)The following example uses a multi line comment to explain the code:


Basics of Javascript , javascript v/s java ,vbscript, script tag , noscript tag , implementation of javascript

Objects,Properties,Value,Methods:


Objects:
        - A programing function that models the charachteristics of abstract or
Real “object” using classes.
Properties:
        - A descriptive charachteristics of an object.
Value:
        - The specific quality to the property of an object.
Methods:
        - An action that can be performed by an object.

 

Javascript AND Java:

JavaScript

JAVA

Interpreted (not compiled) by client.

Compiled on server before execution on client.

Variable data types not declared (loose typing).

Variable types must be declared
(strong typing ).

Dynamic binding; object references checked at run time.

Static binding; object references must exist at compile time

Secure; cannot write to hard disk.

Secure; cannot write to hard disk

Code integrated with and embedded in HTML.

 

 

JavaScript and VBScript:

  - JavaScript and VBScript are scripting languages that have similar purposes.
Both extend the capabilities of static Web pages.
- JavaScript was the first scripting language developed for Web page design.
- It has been incorporated into Netscape Navigator browsers since version 2.0.
- VBScript is the Microsoft Web-scripting language, based on the powerful and popular      
Visual Basic language.
- JavaScript is a strong object-based language that relies, for much of its functionality,
on objects and their attendant methods and properties.

V        

<SCRIPT> Tag:

  • The HTML <script> tag is used to insert a JavaScript into an HTML page.
  • Inside <script> tag type attribute is used to specify the scripting language.
  • JavaScript can write into two sections between <HEAD> tag or between <BODY> tag.
  • If user writes code in <body> section then JavaScript code will be executed immediately after the page has been load.
  • If user writes code in <head> section then JavaScript code will be executed depends on user’s requirement.

Syntax:
<HTML>
<BODY>
<SCRIPT TYPE = “TEXT/JAVASCRIPT”>
                                     . . . .                                                      
      All JavaScript code will </SCRIPT>                                                                 
</HTML>

Attributes of <SCRIPT> Tag:

1)language:This indicates the scripting language of the code as specifier.

                   EX:<script language=”javascript”>

2)type: This indicates the scripting language of the code as content - type.

                  EX:<script type=”text/javascript”>

3)src:Points to an external resource where the script code is declared.

The <NOSCRIPT> Tag.

  • You should be aware that your users may have older browsers that do not support JavaScript, or may disable execution of JavaScript code within their browsers. If so, you can use the HTML <NOSCRIPT> tag to render content for these users.

Example:
<script type="text/javascript">
<h1>This is a SCRIPT TAG Example</h1>
</script>
<noscript>
<h1>This is a NOSCRIPT TAG Example</h1>
</noscript>

Where to Put the JavaScript?
- JavaScripts in a page will be executed immediately while the page loads into the browser.  
- This is not always what we want. Sometimes we want to execute a script when a page  
loads, other times when a user triggers an event.

 Scripts in the head section: Scripts to be executed when they are called, or when an
event is triggered, go in the head section.
<html>
<head>
<script type="text/javascript">
document.write("Shree Solution Junagadh");
</script>
</head>
</html>

Scripts in the body section: Scripts to be executed when the page loads go in the body
section. When you place a script in the body section it generates the content of the page.
<html>
<head>
<script type="text/javascript">
document.write("Shree Solution Junagadh");
</script>
</head>
</html>

Scripts in both the body and the head section: You can place an unlimited number of
scripts in your document, so you can have scripts in both the body and the head section.
<html>
<head>
<script type="text/javascript">
document.write("Shree Solution Junagadh");
</script>
</head>
<body>
<script type="text/javascript">
document.write("Shree Solution Junagadh");
</script>
</body>

</html>


Explain javascript merits and demerits of it.



Java Script:
- JavaScript is the most popular scripting language on the internet, and works in all
   major browsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari.
- JavaScript is a language that is used to make web pages interactive.
- 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.
- Everyone can use JavaScript without purchasing a license.
- Using JavaScript user can add events on your website.
- Using JavaScript user can check the data before it is submitted to the server.

What can a JavaScript do?
·        JavaScript gives HTML designers a programming tool
·        JavaScript can put dynamic text into an HTML page
·        JavaScript can react to events
·        JavaScript can read and write HTML elements
·        JavaScript can be used to validate data
·        JavaScript can be used to detect the visitor's browser
·        JavaScript can be used to create cookies

Advantages of the Javascript:
-         Speed.
-         Easy to use.
-         Versatility.
-         Reduce server Load.
-         Javascript validation.
-         Dynamic Image Effect.

Disadvantages of the Javascript:
-         Security.
-         Reliance on End User.
-         Extending Coding.
-         Reduces Search Engine Friendliness.

all types of cursor with example in oracle



Transaction: us a logical unit of work that is composed of one or more DML or DDL statements. A transaction must be either saved or rolled back.
COMMIT: when you manipulate the data all the DML operation affected in the temporary area and database remains unaffected from all these changes. If you want to store these changes to the database, you need to COMMIT the transaction.
ROLLBACK: means undoing any changes that have occurred in the current transaction. Oracle undoes some or all changes made by your session to the database in the current transaction.
SAVEPOINT: is used to mark a specific point in current transaction. SAVEPOINT gives a name to and mark a point in the processing of current transaction. It allows you to ROLLBACK TO that point.
CURSOR
CURSOR provides you a way to select multiple records from the database and process each record individually inside PL/SQL program. The set of rows returned by multi-query is called result set of active set. There are two types of cursors supported by PL/SQL.
1. Implicit Cursor      2. Explicit Cursor
Implicit Cursor
Explicit Cursor
These cursors are maintained internally by PL/SQL. These are opened and closed automatically when the query is executed.
These cursors are defined with a name and are opened and closed explicitly in a PL/SQL program.
The cursor attributes are prefixed with SQL. (e.g. SQL%FOUND). Because SQL is default name of implicit cursor.
The cursor attributes are prefixed with the cursor name. (e.g. cur%found) where cur is the name of explicit cursor.
The cursor attribute %ISOPEN is always false. Because cursor gets closed automatically after the statement is over.
The %ISOPEN attribute holds the value (TRUE/FALSE) of the status of the cursor.
Only one row can be processed using the SELECT INTO statement.
Any number of rows can be processed.


STEPS REQUIRED FOR EXPLICIT CURSOR:

1. Declare the cursor: in this process, select statement associated with cursor is defined. Syntax:
Cursor is select statement;
2. Open the cursor: in this process when cursor is opened the select statement associated with cursor is executed. Syntax:
Open [(parameter_list)];
3. Fetch rows from the cursor: in this step, one row is retrieved from the active set and stores it in variables for further processing. Syntax:
Fetch into ;
4. Close the cursor: in this step the cursor is closed. The close statement disables the cursor. You can reopen it. Syntax:            close ;

CURSOR ATTRIBUTES: cursor has four attributes:
1.      %NOTFOUND Attribute: rows are fetched from the cursor’s active set one at a time. If the last fetch returned a row %NOTFOUND evaluates to FALSE. If the last fetch failed to return a row then %NOTFOUND evaluates to TRUE.
2.      %FOUND Attribute: is logical opposite of %NOTFOUND. %FOUND evaluates to TRUE if the last fetch returned a row or FALSE if no row was returned.
3.      %ROWCOUNT Attribute: when cursor is opened, %rowcount is zero. When the records are fetched from active set it is incremented by one each time. It returned how many records are fetched from the active set.
4.      %ISOPEN Attribute: evaluates to TRUE if cursor is open, otherwise it evaluates to FALE.

Write the PL/SQL script to display the ename, job, sal and deptno from the emp table.
DECLARE
CURSOR CUR_EMP IS SELECT ENAME, JOB, SAL, DEPTNO FROM EMP;
RS CUR_EMP%ROWTYPE;       --cursor-based record
BEGIN
OPEN CUR_EMP;
LOOP
FETCH CUR_EMP INTO RS;
EXIT WHEN CUR_EMP%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(RS.ENAME || ‘ ‘ || RS.SAL || ‘ ‘ RS.JOB || ‘ ‘|| RS.DEPTNO);
END LOOP;
CLOSE CUR_EMP;
END;

Write a PL/SQL script to increase the salary as per following criteria:
SALARY AMT                     INCREMENTED BY
<1200 span="" style="mso-tab-count: 5;">                                                  8%
<2500 span="" style="mso-tab-count: 5;">                                                  12%
<4500 span="" style="mso-tab-count: 5;">                                                  15%
OTHERWISE                                   20%
DECLARE
CURSOR CUR_EMP IS SELECT EMPNO, SAL FROM EMP;
RS CUR_EMP%ROWTYPE;
BEGIN
OPEN CUR_EMP;
LOOP
FETCH CUR_EMP INTO RS;
IF RS.SAL <1200 span="" then="">
UPDATE EMP SET SAL = SAL *1.08 WHERE EMPNO=RS.EMPNO;
ELSIF RS.SAL <2500 span="" then="">
UPDATE EMP SET SAL = SAL *1.12 WHERE EMPNO=RS.EMPNO;
ELSIF RS.SAL <4500 span="" then="">
UPDATE EMP SET SAL = SAL *1.15 WHERE EMPNO=RS.EMPNO;
ELSE
UPDATE EMP SET SAL = SAL *1.2 WHERE EMPNO=RS.EMPNO;
END IF;
CLOSE CUR_EMP;
END;

Parameterized Cursors: a cursor can receive values provided by you, such cursors are known as Parameterized cursors.
Cursor cur_name (parameter datatype,…..) is select statement;
We can provide value for these parameters at the time of opening cursor as per following syntax:
Open cur_name(value, …);
Write the PL/SQL script to display the ename, job, sal of particular dept that is input by user using parameter.
DECLARE
CURSOR CUR_EMP(DNO NUMBER) IS SELECT ENAME, JOB, SAL FROM EMP WHERE DEPTNO = DNO;
RS CUR_EMP%ROWTYPE;       --cursor based record
DEPT_NO NUMBER;
BEGIN
DEPT_NO := &DEPTNO;
OPEN CUR_EMP(DEPT_NO);
LOOP
FETCH CUR_EMP INTO RS;
EXIT WHEN CUR_EMP%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(RS.ENAME || ‘ ‘ || RS.SAL || ‘ ‘|| RS.JOB);
END LOOP;
CLOSE CUR_EMP;
END;

CURSOR FOR LOOP:
PL/SQL provides a special kind of FOR loop to process the rows returned in an explicit cursor. In a Cursor FOR Loop, a declared cursor is Opened, Fetched and Closed automatically when all of the rows have been processed. Syntax:

FOR IN

LOOP
--STATEMENTS TO BE EXECUTED
END LOOP;
Write a PL/SQL script to display the name, salary and bonus (salary * .12) for each emp using cursor for loop.
DECLARE
CURSOR CUR_EMP IS SELECT ENAME, SAL, SAL *1.2 ‘BONUS’ FROM EMP;
BEGIN
FOR RS IN CUR_EMP LOOP
DBMS_OUTPUT.PUT_LINE(RS.ENAME || ‘ ‘ || RS.SAL ||’ ‘ ||RS.BONUS) ;
END LOOP;
END;
CURSOR FOR LOOP USING USB-QUERY:
Writing a sub-query in place of cursor name in the cursor For Loop can do this. Syntax:

FOR IN LOOP

--STATEMENTS TO BE EXECUTED
END LOOP;

Write a PL/SQL script to display the name, salary for each emp using cursor for loop.
BEGIN
FOR RS IN (SELECT ENAME, SAL FROM EMP)
LOOP
DBMS_OUTPUT.PUT_LINE(RS.ENAME || ‘ ‘ || RS.SAL) ;
END LOOP;
END;