Swati Lathia

Learning ways

JavaScript Tutorial 2

JavaScript Loop Control Statements

  • JavaScript provides full control to handle loops and switch statements.
  • There may be a situation when you need to come out of a loop without reaching at the end.
  • There may also be a situation when you want to skip a part of your code block and start the next iteration of the loop.
  • To handle these kinds of 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 exit a loop early, breaking out of the enclosing curly braces.
  • Look at the following example how the loop breaks out early once x reaches 5 and reaches to document.write (..) statement just below to the closing curly brace.
var x=1;
while(x<10) 
{
    	if (x==5) 
	{
      		break;   // breaks out of loop completely
       	}
        document.write(x + "<br>");
        x=x+1;
 }   

The continue Statement

  • The continue statement tells the interpreter to immediately skip the remaining code block & start the next iteration of the loop.
  • When a continue statement is encountered, the program flow moves to the loop check expression immediately and if the condition remains true, then it starts the next iteration, otherwise the control comes out of the loop.
  • The following example illustrates how the continue statement is used to skip printing when the index held in variable x reaches 5.
var x = 1;
while (x<10) 
{
               x = x + 1;
               if (x==5) {
                  continue;   // skip rest of the loop body
               }
               document.write(x+"<br>");
}

JavaScript User Define Functions

  • A function is a group of reusable code which can be called anywhere in your program.
  • This eliminates the need of writing the same code again and again.
  • Functions allow a programmer to divide a big program into a number of small and manageable functions.

Function Definition

  • To define a function in JavaScript, use function keyword which is followed by a unique function name, a list of parameters (might be empty), and a statement block surrounded by curly braces.

Syntax

function functionname(parameter-list) 
{
         statements
}

Example : It defines a function called demo that takes no parameters.

function demo()
{
			Document.write(“Hello, I am User defined function”);
}

How to call a function?

  • To call a function wherever & whenever in the script, you simply need to write the name of that function as shown in the following code.
<html>
<head>   
      <script type = "text/javascript">
      function demo() 
      {
            document.write ("Hello, I am user defined function..");
      }
      </script>
</head>
<body>
      <form>
         <input type = "button" value=”Click Here” onclick = "demo()">
      </form>      
</body>
</html>
  • In above example, I have used onclick event, means function is invoked when a user clicks on a button.

Function Parameters

  • UDF gives a facility to 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.
<html>  
	<head>
	<script type="text/javascript">  
        function demo(name,city) 
        {
	     document.write("Hi I am ",name," & I am from ",city);
        }       
	</script>  
	</head>
        <body>  
	<form>
	<input type=button value="Click here" onclick='demo("Swati Lathia","Jamnagar");'
	</form>
	</body>  
</html>

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.

JavaScript Dialog Boxes

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

Alert Dialog Box

  • An alert dialog box is mostly used to give a warning message to the users.
  • For example, if an input field requires to enter number but the user provides any input other than number, then as a part of validation, you can use an alert box to give a warning message that “user has to enter numbers only”.
  • Alert box gives only one button “OK” to select and proceed.

Example

<head>   
      <script type = "text/javascript">
         function demo() 
         {
               alert ("This is an alert!");
         }
      </script>     
 </head>
 <body>
      <form>
         <input type = "button" value = "Click Me" onclick = "demo();" />
      </form>     
 </body>

Confirmation Dialog Box

  • A confirmation dialog box is mostly used to take user’s permission (ok or cancel) on any option.
  • It displays a dialog box with two buttons: OK and Cancel.
  • If the user clicks on the OK button, the window method confirm() will return true. If the user clicks on the Cancel button, then confirm() returns false.

Example

<head>   
      <script type = "text/javascript">
            function getConfirmation() 
            {
               var a = confirm("Do you want to continue ?");
               if( a == true ) 
               {
                  document.write ("User wants to continue!");
                  return true;
               } 
               else 
               {
                  document.write ("User does not want to continue!");
                  return false;
               }
            }
       </script>     
</head>
<body>
      <form>
         <input type = "button" value = "Click Me" onclick = "getConfirmation();">
      </form>      
</body>

Prompt Dialog Box

  • The prompt dialog box is used to get the value from user.
  • It gives a textbox in which you can enter your value.
  • 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 and (ii) a default string to display in the text box.
  • This dialog box has two buttons: OK and Cancel.
  • If the user clicks the OK button, the window method prompt() will return the entered value from the text box.
  • If the user clicks the Cancel button, the window method prompt() returns null.
<head>     
      	<script type = "text/javascript">
               function getValue() 
               {
                  var name = prompt("Enter your name : ", "Hello");
                  document.write("You have entered : " + name);
               }
        </script>      
</head>
<body>
     <form>
         <input type = "button" value = "Click Me" onclick = "getValue();">
      </form>      
</body>
  • In above example, you are asked to enter your name, if your provide your name, it will give an out put like :” You have entered Swati Lathia”.
  • If you have not provided any value, it will give an output like: ” You have entered Hello”. Here “Hello” is the default value which given in prompt ().

JavaScript Arrays

  • The Array lets you store multiple values in a single variable. It stores a collection of elements of the same type.

Syntax

var subject = new Array( "HTML", "Networking", "Language C", " Computer Fundamentals");
  • 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.
  • You can create array by simply assigning values as follows –
  • var subject = [ “HTML”, “Networking”, “Language C”, ” Computer Fundamentals”];
  • You can use ordinal numbers to access and to set values inside an array as follows.
  • subject[0] is the first element
  • subject[1] is the second element
  • subject[2] is the third element
  • subject[3] is the fourth element
   <body>     
      <script type = "text/javascript">
             		  var a= new Array(10,20,30,40);
		alert(a[0]);
		alert(a[1]);
		alert(a[2]);
		alert(a[3]);
      </script>      
   </body>
Scroll to top