JavaScript for Computer Science and MCA students

Explain kinds of procedures in VB script.

What is Procedure?
  • It is an assignment that asks to VBScript to perform besides or to complete the normal flow of the program.
  • It is created to work in conjunction with the control events of a script.
  • VBScript procedures are used mainly for code organization and reuse.
  • There are two kinds of procedures in VBScript
    1. Sub Procedure
    2. Function Procedure
  • A procedure can be included in the body of an HTML, but to separate the script behavior from the rest of the file, it is usually a good idea to include the procedures in the head section of the file.
1. Sub Procedure:
  • It is a series of VBScript statements that perform actions, but don't return a value.
  • It can take arguments like constants, variables or expressions that are passed by a calling procedure.
  • It can be called without 'call' keyword.
  • They are always enclosed within 'Sub' and 'End Sub' statements.
Declaration of Sub Procedure
Sub procedure_name(arg1, arg2, . . .)
     //Statements
End Sub

Example
<script type = “text/vbscript”>
     Sub outputMessage()
          document.write(“CareerRide Info”)
     End Sub
     call outputMessage()
</script>

Points to be considered
The 'Sub' keyword is followed by the name that is given to the procedure.

The function name follows the same rules as a variable name:
  • The name must start with a letter.
  • A procedure name can contain letters, numbers and characters and '&' (Spaces are not allowed).
  • The variables are case sensitive.
  • Do not forget to close the braces.
  • The number of open braces must be equal to the number of closed parentheses.
  • Once this is done, the procedure will not run until it is called somewhere in the script.
2. Function Procedure:
  • It declares the name, arguments and code that form the body of a Function Procedure.
  • It is a series of statements, enclosed by the Function and End Function statements.
  • It can perform actions and can return a value.
  • It can take arguments that are passed to it by a calling procedure.
  • It returns a value by assigning a value to its name.
  • If a Function Procedure has no arguments, then its function statement must include an empty set of parentheses.
Declaration of Function Procedure
Function procedure_name (arg1, arg2, . . . )
     List of Statements
End Function

Example
FUNCTION myFunc()
     myFunc = Date()
END FUNCTION

Calling a Function
To execute a function, just call it by writing its name (case sensitive) followed by an open parenthesis and then a closing parenthesis:
FuntionName()
To call a procedure:
Call Procedure_name()

It is possible to call a procedure as follows:

Procedure_Name arguments

Arguments

ArgumentDescription
PublicIt indicates that the Function procedure is accessible to all other procedures in all scripts.
DefaultIt is used only with the 'Public' keyword in a 'Class' block to indicate that the Function procedure is the default method for the class. An error occurs if more than one default procedure is specified in a class.
PrivateIt indicates that the Function procedure is accessible only to other procedures in the script where it is declared.
nameName of the function, follows standard variable naming conventions.
statementsAny group of statements to be executed within the body of the Function procedure.
expressionIt returns value of the function.
arglistList of variables representing arguments that are passed to the function procedure when it is called. Commas separate multiple variables.

The 'arglist' Arguments

ByValIt indicates that the argument is passed by value.
ByRefIt indicates that the argument is passed by reference. If ByVal and ByRef are omitted, the default is ByRef.
varnameName of the variable representing the argument, follows standard variable naming conventions.

Explain Event handling in JavaScript with suitable example.

What is Event handling in JavaScript?
  • It is a software routine that processes action, such as keystrokes and mouse movements.
  • It is the receipt of an event at some event handler from an event producer and subsequent processes.
Functions of Event Handling:
  • It identifies where an event should be forwarded.
  • It makes the forward event.
  • It receives the forwarded event.
  • It takes some kind of appropriate action in response, such as writing to a log, sending an error or recovery routine or sending a message.
  • The event handler may ultimately forward the event to an event consumer.
Event Handler in JavaScript:
It executes a segment of a code based on certain events occurring within the application, such as onClick, onLoad etc.

It can be divided into two parts
I. Interactive Event Handlers
II. Non-Interactive Event Handlers

I. Interactive Event Handlers:
  • This type of event handler depends on the user interactivity with the form or the document.
  • For example, onMouseOver is an interactive event handler because it depends on the user's action with the mouse.
II. Non-Interactive Event Handlers:
  • This type of event would be onLoad, because it automatically executes JavaScript code without the user's interactivity.
Event HandlerDescription
onAbortIt executes when the user aborts loading an image.
onBlurIt executes when the input focus leaves the field of a text, text area or a select option.
onChangeIt executes when the input focus exits the field after the user modifies its text.
onClickIn this, a function is called when an object in a button is clicked, a link is pushed, a checkbox is checked or an image map is selected. It can return false to cancel the action.
onErrorIt executes when an error occurs while loading a document or an image.
onFocusIt executes when input focus enters the field by tabbing in or by clicking but not selecting input from the field.
onLoadIt executes when a window or image finishes loading.
onMouseOverThe JavaScript code is called when the mouse is placed over a specific link or an object.
onMouseOutThe JavaScript code is called when the mouse leaves a specific link or an object.
onResetIt executes when the user resets a form by clicking on the reset button.
onSelectIt executes when the user selects some of the text within a text or texarea field.
onSubmitIt calls when the form is submitted.
onUnloadIt calls when a document is exited.

Explain how JavaScript objects are different from C++/Java objects.

Sr. No.JavaScript ObjectsC++/Java Objects
1.It does not make heavy use of inheritance.It makes heavy use of inheritance.
2.It cannot use encapsulation, overloading and polymorphism.It uses encapsulation, overloading and polymorphism.
3.It cannot used to develop standalone applications.It can used to develop standalone applications.
4.It is visible in the document's source.It is not visible in the document's source.
5.It is an Object-based.It is an Object-oriented.
6.Data types are not declared.Data types must be declared.
7.It is a loosely-typed language.It is a strongly-typed, object-oriented, complex programming language.
8.It is much less secure.It is secure.
9.The code uses built-in, extensible objects, but no classes or inheritance.Applet consists of object classes with inheritance.
10.It is not compiled by the client machine.It is compiled on the server before execution on a client machine.

How to use array in JavaScript? Also explain types of array?

What is JavaScript?
  • It is an object-oriented computer programming language which is commonly used to create interactive effects within web browsers.
  • It is an interpreted programming or script language from Netscape.
  • The scripting languages are easier and faster to code in than the more structured and compiled languages such as C and C++.
  • It takes longer to process than compiled languages, but it is very useful for shorter programs.
How to use array in JavaScript?
JavaScript arrays are used to store multiple values in a single variable.

Creating and Initializing Arrays in JavaScript:
var arr = []; // Creating an Array
var arr1 = [1, 2, 3]; // Initializing an Array

Multidimensional Array in JavaScript:
var arr2 = [
                    [1, 2, 3],
                    ['a', 'b', 'c'],
                    ['x', 'y', 'z']
               ];

Iteration through Arrays in JavaScript:
function show_array(arr)
{
     for (var i=0; i < arr.length; i++ )
     {
          document.write(array[i]);
          document.write('<br/>');
     }
}
var arr1 = [1, 2, 3];
show_array(arr1);

Array Properties:

Array PropertiesDescription
ConstructorIt returns a reference to the array function that created the object.
IndexIt represents the zero-based index of the match in the string.
LengthIt reflects the number of elements in an array.
InputIt presents only in array created by regular expression matches.
PrototypeIt allows you to add properties and methods to an object.

Array Methods:

MethodsDescription
concat()It returns a new array comprised of this array joined with other arrays and values.
every()It returns a true if every element in this array satisfies the provided testing function.
filter()It creates a new array with all of the elements of this array for which the provided filtering function returns true.
indexOf()It returns the first index of an element within the array equal to the specified value.
join()It joins all elements of an array into a string.
pop()It removes the last element from an array and returns that element.
push()It adds one or more elements to the end of an array and returns the new length of the array.
reverse()It reverses the order of the elements of an array.
sort()It represents the source code of an object.

Explain client side & server side scripting.

Client-Side:
  • It is an important part of the Dynamic HTML (DHTML).
  • JavaScript is the main client-side scripting language for the web.
  • The scripts are interpreted by the browser.
  • It is used to make web pages change after they arrive at the browser.
  • It is useful for making the pages a bit more interesting and user-friendly.
  • It provides useful gadgets such as calculators, clocks etc.
  • It enables interaction within a webpage.
  • This scripting languages include JavaScript.
  • It is affected by the processing speed of the user's computer.
Operation of Client-Side:
client-side-scripting
  • The user requests a web page from the server.
  • The server finds the page and sends it to the user.
  • The page is displayed on the browser with any scripts running during or after the display.
  • It is used to make web pages change after they arrive at the browser.
  • These scripts rely on the user's computer. If the computer is slow, then they may run slow.
  • These scripts may not run at all if the browser does not understand the scripting language.
Server-Side:
  • It is a technique used in web development.
  • The server-side environment that runs a scripting language is a web server.
  • It is used to provide interactive web sites that interface to databases or other stores on the server.
  • A user's request is fulfilled by running a script directly on the web server to generate dynamic HTML pages.
  • It is different from client-side scripting where scripts are run by the viewing web browser, usually in JavaScript.
  • It tends to be used for allowing users to have individual accounts and providing data from databases.
  • Server-side allows a level of privacy, personalization and provision of information that is very powerful.
  • This scripting languages include ASP.NET and PHP.
  • It does not rely on the user having specific browser or plug-in.
  • It is affected by the processing speed of the host server.
Operation of Server-Side:
server-side-scripting
  • The user (client) requests a web page from the server.
  • The script in the page is interpreted by the server, creating or changing the page content to suit the user(client) and the passing data around.
  • The page in its final form is sent to the user(client) and then cannot be changed using server-side scripting.
  • It tends to be used for allowing users to have individual accounts and provides data from databases.
  • Server-side scripting allows a level pf privacy, personalization and provision of information that is very useful.
  • These scripts are never seen by the user.
  • Server-side script runs on the server and generate results which are sent to the user.
  • Running all the scripts puts a lot of load onto a server but not on the user's system.

Explain with example primitive data type of VBScript.

What is VBScript?
  • This is a scripting language developed by Microsoft.
  • It is based on Visual Basic.
  • VBScript is designed as 'lightweight' language with a fast interpreter for use in a wide variety of Microsoft environments.
Functions of VBScript:
  • Its functionality in a web environment is dependent upon either an ASP engine or the windows scripting host.
  • It must be used on a Windows hosting platform.
  • VBScript must be executed within a host environment.
  • It can be effectively used for automating day to day office tasks as well as monitoring in the Windows-based environment.
VBScript Data types:
  • It has only one data type called a Variant.
Variant Data type:
  • It is a special kind of data type which contains different kinds of information.
  • It contains either numeric or string information.
  • It behaves as a number when you use it in a numeric context and as a string when you use it in a string context, depending on how it's used.
Variant Subtypes:
Following table shows the variant subtypes:

Data TypesRange
EmptyVariant is uninitialized. Value is 0 for numeric variables or a zero-length string ("") for string variables.
NullVariant intentionally contains no valid data.
BooleanEither True or False.
Byte0 to 255
Integer-32,768 to 32,767
Currency-922,337,203,685,477.5808 to 922,337,203,685,477.5807
Long-2,147,483,648 to 2,147,483,647
SingleFor negative values: -3.402823E38 to -1.401298E-45

For positive values: 1.401298E-45 to 3.402823E38
DoubleFor negative values: -1.79769313486232E308 to -4.94065645841247E-324

For positive values: 4.94065645841247E-324 to 1.79769313486232E308
Date (Time)It represents a date between January 1, 100 to December 31, 9999.
StringIt contains a variable-length string that can be up to approximately 2 billion characters in length.
ObjectIt contains an object.
ErrorIt contains an error number.

What do you understand the uses of JavaScript for FORM Validations? Explain with an example.

What is JavaScript?
  • It is an object-oriented computer programming language which is commonly used to create interactive effects within web browsers.
  • It is an interpreted programming or script language from Netscape.
  • The scripting languages are easier and faster to code in than the more structured and compiled languages such as C and C++.
  • It takes longer to process than compiled languages, but it is very useful for shorter programs.
What is Form Validation?
  • Checking the correctness of the values entered by the user on the fly is called as Form Validation.
  • It is important to validate the form submitted by the user because it can have inappropriate values, so the validation is must.
Uses of JavaScript for FORM Validations?
  • A form validation can be done by a JavaScript.
  • It can save a lot of unnecessary calls to the server as all processing is handled by the web browser.
  • It can prevent people from leaving fields blank from entering too little or too much or from using invalid characters.
  • When form input is important, it should always be verified using a secure server-side script. Otherwise a browser with JavaScript disabled, or a hacker trying to compromise your site, can easily submit invalid data.
Example:
<script>
function validateform()
{
     var user_name = document.myform.name.value;
     var password = document.myform.password.value;
     if (name==null || name=="")
     {
          alert("Name can't be blank");
          return false;
     }
     else if(password.length<6)
     {
          alert("Password must be at least 6 characters long.");
          return false;
     }
}
</script>
<body>
<form name = "myform" method = "post" action="abc.jsp" onsubmit="return validateform()" >
Name: <input type = "text" name = "name">

Password: <input type = "password" name = "password">

<input type = "submit" value = "register">
</form>

What do you understand the JavaScript Variables? Explain with an example.

What is JavaScript?
  • It is an object-oriented computer programming language which is commonly used to create interactive effects within web browsers.
  • It is an interpreted programming or script language from Netscape.
  • The scripting languages are easier and faster to code in than the more structured and compiled languages such as C and C++.
  • It takes longer to process than compiled languages, but it is very useful for shorter programs.
What is JavaScript Variables?
  • It is simply a name of storage location.
  • It is also known as identifiers.
  • These are the containers for storing the data values.
Declaration of JavaScript Variable:
  • Creating a variable in JavaScript is called declaring a variable.
  • It can be declared with the 'var' keyword.
var a;
var a = 10;


Types of JavaScript Variable:

There are two types of variable
1. Global Variable
2. Local Variable

1. Global Variable
  • It is accessible from any function.
  • A variable is declared outside the function or declared with window object is known as global variables.
Example
<script>
var x = 10; // Global Variable
function display()
{
     document.write(x);
}
fucntion show()
{
     document.write(x);
}
a(); //Calling JavaScript Function
b(); //Calling JavaScript Function
</script>

Output:
10     10

2. Local Variable
  • It is declared inside block or function.
  • It is accessible within the function or block only.
Example
<script>
function display()
{
     var a = 10; //Local Variable
}
</script>

Explain FOR Loop and illustrate with code examples.

What is FOR Loop?
  • It is a programming language control statement.
  • It allows code to be executed repeatedly.
  • It is a repetition control structure that allows you to efficiently write a loop which executes a specific number of times.
Syntax
for (Initialization; Condition; Iteration (Increment/Decrement))
{
     Statements1;
     Statements2;
}

Example
for (i = 0; i < = 10; i + +) // i + + → Increment
{
     //Statements;
}
for (i = 0; i > = 10; i - -) // i - - → Decrement
{
     //Statements;
}

Flow Diagram of 'For' Loop:
flow diagram for loop
Flow of FOR Loop:
  • The initialization step is executed first and only once. It allows to declare and initialize the variables.
  • The next step 'condition' is evaluated. If the condition is true, the body of the loop is executed. If the condition is false, the body of the loop does not execute and the control jumps to the next step just after the 'for' loop.
  • After the body of the 'for' loop executes, the flow of control jumps back up to the iteration statement, it is done either increment or decrement. It allows to update any loop control variables.
  • The condition is now evaluated again. If the condition is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). And if the condition becomes false, the 'for' loop terminates.
Example:
<html>
<head>
<script language = "javascript">
var add = 0;
for (var i = 1; i <= 20; i++) // Initialization; Condition; Iteration (Increment)
{
     add = add + i; // Body of Loop
}
document.write("Addition = " + add);
</script>
</head>
</html>

Output:
Addition = 210

Explain BREAK Loop and illustrate with code examples.

  • BREAK statement provides to control the flow of the program.
  • It is used to break the loop of the switch statement.
  • If the BREAK statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
Syntax
break;

Flow diagram of BREAK Statement:
flow diagram of break loop
Example
<html>
<body>
<script type="text/javascript">
<!--
     var a = 0;
     document.write("Entering the loop<br /> ");
     while (a < 5)
     {
          if (a == 5)
          {
               break; // breaks out of loop completely
          }
          a = a + 1;
          document.write( a + "<br />");
     }
     document.write("Exiting the loop<br /> ");
//-->
</script>
</body>
</html>

Output
Entering the loop
1
2
3
4
5
Exiting the loop

Write a Javascript code to check the password strength when user is typing his password. (Do not write code on submit button)
               Password length >= 10                    Strong
               Password length < 10 and >=5        Medium
               Password length < 4                      Weak

<html>
<body>
<script type="text/javascript">
/*Method to check password strength*/

function checkPasswordLength()
{
     /*Get value entered by user in password field*/
     var passwordTxt = document.getElementById("pass").value;

     /*Get label element where we are going to display password strength*/
     var labelPassStrength = document.getElementById("passStrength");

     /*Read length of password*/
     var lengthOfPassword = passwordTxt.length;

     if(lengthOfPassword>=10)
          labelPassStrength.innerHTML = "Strong";

     else if(lengthOfPassword<10 && lengthOfPassword >= 5)
     {
          labelPassStrength.innerHTML = "Medium";
     }
     else
     {
          labelPassStrength.innerHTML = "Weak";
     }
}
</script>

     <input type="password" id="pass" onkeyup="checkPasswordLength();" />
     <label id="passStrength"></label>

</body>
</html>

Output:
medium  output weak  output strong