0% found this document useful (0 votes)
11 views31 pages

Unit-1 Question and Answers

The document provides a comprehensive overview of JavaScript, covering its features, differences from Java, data types, conditional statements, loop structures, functions, objects, event handling, and the Document Object Model (DOM). It also briefly discusses VBScript, comparing it with JavaScript and outlining its features and data types. The content is structured as a series of questions and answers, making it a useful reference for understanding JavaScript and its applications in web development.

Uploaded by

Anand Kalyan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views31 pages

Unit-1 Question and Answers

The document provides a comprehensive overview of JavaScript, covering its features, differences from Java, data types, conditional statements, loop structures, functions, objects, event handling, and the Document Object Model (DOM). It also briefly discusses VBScript, comparing it with JavaScript and outlining its features and data types. The content is structured as a series of questions and answers, making it a useful reference for understanding JavaScript and its applications in web development.

Uploaded by

Anand Kalyan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Unit-1 Ques ons and Answers

Q1. Explain various features of JavaScript with examples.


JavaScript is a versa le and powerful scrip ng language widely used for web
development. It has several features that make it essen al for crea ng interac ve and
dynamic websites:
1. Client-Side Execu on: JavaScript runs directly in the user's web browser without
requiring server-side execu on, making it faster and reducing server load.
Example:
<bu on onclick="alert('Hello, User!')">Click Me</bu on>
2. Dynamic Typing: Unlike languages like Java, JavaScript allows variables to hold
different types of data during run me.
Example:
let value = 42; // Number
value = "JavaScript"; // Now a String
console.log(value);
3. Object-Oriented: JavaScript supports object-oriented programming principles,
allowing developers to create reusable code modules.
Example:
const car = { brand: "Tesla", model: "Model S", speed: 200 };
console.log(car.brand); // Output: Tesla
4. Event Handling: JavaScript makes it easy to respond to user interac ons such as
clicks, mouse movements, and form submissions.
Example:
document.getElementById("btn").addEventListener("click", () => alert("Bu on Clicked!"));
5. Pla orm Independent: JavaScript can run on any pla orm and browser without
modifica on, making it highly portable.
6. Built-In Libraries: JavaScript provides many built-in libraries for performing complex
tasks like anima ons, DOM manipula on, and HTTP requests.
7. Asynchronous Programming: JavaScript supports asynchronous opera ons using
promises, async/await, and callback func ons.
Example:
setTimeout(() => console.log("Task completed!"), 1000);
JavaScript con nues to evolve, with features like ES6 introducing new capabili es such as
template literals, arrow func ons, and destructuring.

Q2. Dis nguish between Java and JavaScript with examples.


Java and JavaScript are o en confused due to their names, but they are fundamentally
different. Here's a detailed comparison:
Feature Java JavaScript
Type Programming Language Scrip ng Language
Compila on Compiled into bytecode Interpreted
Execu on Environment Requires JVM Runs in a browser
Syntax Strongly typed Loosely typed
Use Case Backend development, apps Web development, interac vity

Java Example:
public class Main {
public sta c void main(String[] args) {
System.out.println("Hello, Java!");
}
}

JavaScript Example:
console.log("Hello, JavaScript!");
Java is suitable for complex, backend systems, whereas JavaScript dominates web front-
end interac vity.
Q3. Explain various places where JavaScript can be placed in HTML by using examples.
JavaScript can be placed in an HTML document in three main ways:
1. Inline JavaScript: JavaScript code is directly wri en inside an HTML tag’s a ribute.
Example:
<bu on onclick="alert('Inline JavaScript')">Click Me</bu on>
2. Internal JavaScript: JavaScript is included within the <script> tag inside the HTML
file.
Example:
<script>
document.write("Internal JavaScript Example");
</script>
3. External JavaScript: JavaScript is wri en in a separate file with a .js extension and
linked using the <script> tag.
Example:
<script src="script.js"></script>
Contents of script.js:
alert("External JavaScript Example");
External scripts are reusable and help maintain cleaner HTML files.

Q4. Explain various Data Types available in JavaScript with examples.


JavaScript provides several data types, broadly categorized into primi ve and non-
primi ve types:
1. Primi ve Data Types:
o String: Used for textual data. Example:
let name = "Alice";
console.log(name); // Output: Alice
o Number: Represents integers and floa ng-point numbers. Example:
let score = 95.5;
console.log(score); // Output: 95.5
o Boolean: Represents true or false values. Example:
let isAc ve = true;
o Undefined: A variable declared but not assigned a value. Example:
let x;
console.log(x); // Output: undefined
o Null: Represents an inten onal absence of value. Example:
let data = null;
o Symbol: A unique and immutable value.
2. Non-Primi ve Data Types:
o Object: Used for storing collec ons of data. Example:
let user = { name: "Alice", age: 30 };
Data types help define variables and perform opera ons effec vely.

Q5. Explain various Condi onal Statements available in JavaScript by using examples.
JavaScript provides mul ple ways to implement decision-making through condi onal
statements:
1. if Statement: Executes a block of code if the condi on is true. Example:
let age = 20;
if (age >= 18) {
console.log("Eligible to vote");
}
2. if-else Statement: Executes one block if the condi on is true, another if it’s false.
Example:
let age = 16;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
3. if-else if-else Ladder: Mul ple condi ons are checked sequen ally. Example:
let marks = 85;
if (marks >= 90) {
console.log("Grade A");
} else if (marks >= 70) {
console.log("Grade B");
} else {
console.log("Grade C");
}
4. Switch Statement: Suitable for evalua ng mul ple cases of a single expression.
Example:
let color = "red";
switch (color) {
case "red": console.log("Stop"); break;
case "green": console.log("Go"); break;
default: console.log("Invalid color");
}
Each of these constructs ensures flow control in JavaScript programs.

Q6. Explain Various Itera ve or Loop Structures in JavaScript by using examples.


JavaScript provides several loop structures to execute a block of code mul ple mes,
depending on a condi on. These include for, while, and do...while loops.
1. For Loop:
 Executes a block of code a specified number of mes.
 Syntax:
for (ini aliza on; condi on; increment/decrement) {
// Code block to execute
}
Example:
for (let i = 1; i <= 5; i++) {
console.log("Itera on: " + i);
}
2. While Loop:
 Executes a block of code as long as the condi on is true.
 Syntax:
while (condi on) {
// Code block to execute
}
Example:
let count = 1;
while (count <= 5) {
console.log("Count: " + count);
count++;
}
3. Do...While Loop:
 Executes the code block at least once before checking the condi on.
 Syntax:
do {
// Code block to execute
} while (condi on);
Example:
let num = 1;
do {
console.log("Number: " + num);
num++;
} while (num <= 3);
4. For...in Loop:
 Iterates over the proper es of an object.
Example:
const person = { name: "Alice", age: 30 };
for (let key in person) {
console.log(key + ": " + person[key]);
}
5. For...of Loop:
 Iterates over iterable objects like arrays.
Example:
const fruits = ["Apple", "Banana", "Cherry"];
for (let fruit of fruits) {
console.log(fruit);
}
Loops are crucial for tasks involving repe ve ac ons, such as traversing arrays or
processing data.

Q7. How do you create a func on in JavaScript?


A func on is a reusable block of code designed to perform a specific task. Func ons
improve code readability and reduce redundancy.
1. Declaring a Func on:
 Syntax:
func on func onName(parameters) {
// Code to execute
}
 Example:
func on greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
2. Func on Parameters and Return Values:
 Func ons can accept parameters and return values.
 Example:
func on add(a, b) {
return a + b;
}
let result = add(5, 3);
console.log(result); // Output: 8
3. Anonymous Func ons:
 Func ons without names are assigned to variables.
 Example:
const mul ply = func on (x, y) {
return x * y;
};
console.log(mul ply(2, 4)); // Output: 8
4. Arrow Func ons:
 Introduced in ES6, providing a concise syntax.
 Example:
const square = (n) => n * n;
console.log(square(5)); // Output: 25
Func ons are the building blocks of JavaScript programs, enabling modular and efficient
coding.

Q8. What do you mean by Objects, Proper es of an Object, and Methods of an Object?
Objects:
 Objects are collec ons of key-value pairs, represen ng real-world en es with
a ributes and behaviors.
 Syntax:
let objectName = {
property1: value1,
property2: value2,
};
Proper es of an Object:
 A ributes that define the object’s characteris cs.
 Example:
let car = {
brand: "Tesla",
model: "Model S",
year: 2021,
};
console.log(car.brand); // Output: Tesla
Methods of an Object:
 Func ons defined within objects that describe ac ons.
 Example:
let car = {
start: func on () {
console.log("Car started");
},
};
car.start(); // Output: Car started
Objects provide a way to encapsulate data and related func onali es, making them
essen al for object-oriented programming.

Q9. Write a short note on Event Handling in JavaScript.


Event handling in JavaScript allows developers to define behaviors triggered by user
ac ons or browser events, such as clicks, keystrokes, or mouse movements.
1. Adding Event Listeners:
 Use the addEventListener method to a ach event handlers.
 Example:
document.getElementById("btn").addEventListener("click", func on () {
alert("Bu on Clicked!");
});
2. Inline Event Handling:
 Specify event handlers directly in HTML.
 Example:
<bu on onclick="alert('Clicked!')">Click Me</bu on>
3. Common Event Types:
 click: Triggered when an element is clicked.
 mouseover: Triggered when the mouse is over an element.
 keydown: Triggered when a key is pressed.
4. Event Object:
 Provides informa on about the event.
 Example:
document.addEventListener("click", func on (e) {
console.log("X: " + e.clientX + ", Y: " + e.clientY);
});
Event handling enables interac vity and responsiveness in web applica ons.

Q10. Explain Links, Images, and Tables in JavaScript by using examples.


JavaScript enables dynamic manipula on of links, images, and tables on a webpage.
1. Links:
 Modify or create links dynamically.
 Example:
document.getElementById("link").href = "h ps://www.example.com";
2. Images:
 Change image sources or proper es.
 Example:
document.getElementById("img").src = "image2.jpg";
3. Tables:
 Add or remove rows and cells dynamically.
 Example:
let table = document.getElementById("myTable");
let row = table.insertRow(0);
let cell = row.insertCell(0);
cell.innerHTML = "New Cell";
These features empower developers to create dynamic and visually engaging web
applica ons.

Q11. Describe Document Object Model (DOM)


The Document Object Model (DOM) is a programming interface for HTML and XML
documents. It represents the structure of a document as a tree of objects, allowing
developers to manipulate the content, structure, and style of web pages
programma cally.
Key Features of DOM:
1. Tree Structure:
o The DOM represents a document as a tree with nodes such as elements,
a ributes, and text.
Example:
<html>
<body>
<h1>Title</h1>
<p>Paragraph</p>
</body>
</html>
The DOM structure for this document:
 html
 body
 h1
 p
2. Accessing Elements:
o Elements in the DOM can be accessed using methods like:
 getElementById()
 getElementsByClassName()
 querySelector()
Example:
const tle = document.getElementById(" tle");
console.log( tle.textContent);
3. Manipula ng Content:
o Modify text, a ributes, or styles dynamically.
Example:
document.getElementById(" tle").textContent = "New Title";
4. Event Handling:
o Events such as click, mouseover, or keypress can be handled through the
DOM.
Example:
document.getElementById("bu on").addEventListener("click", func on () {
alert("Bu on clicked!");
});
Importance of DOM:
 Dynamic Updates: Enables updates to web pages without reloading them.
 Interac vity: Supports features like anima ons, form valida ons, and interac ve
content.
 Cross-Browser Compa bility: Provides a consistent way to interact with web
documents across browsers.

Q12. Explain Various Features of VBScript


VBScript (Visual Basic Scrip ng Edi on) is a lightweight scrip ng language developed by
Microso . It is primarily used for automa ng tasks in Windows environments and for
adding interac vity to web pages.
Key Features of VBScript:
1. Simple Syntax:
o VBScript uses an easy-to-understand syntax, similar to Visual Basic, making it
beginner-friendly.
o Example:
MsgBox "Hello, World!"
2. Lightweight Language:
o VBScript is small and can be embedded in HTML documents or run as
standalone scripts in Windows.
3. Integra on with HTML:
o Can be used within HTML for client-side scrip ng (in Internet Explorer).
o Example:
<script language="VBScript">
MsgBox "Welcome to VBScript"
</script>
4. Event-Driven Programming:
o Supports event-driven scrip ng to handle user interac ons.
o Example:
<bu on onclick="MsgBox 'Bu on clicked!'">Click Me</bu on>
5. Built-in Func ons:
o Provides various built-in func ons for string manipula on, date handling, and
mathema cal opera ons.
6. Compa bility with Windows:
o VBScript can interact with Windows components like files, registry, and
system se ngs via Windows Script Host (WSH).
7. Error Handling:
o Supports error-handling mechanisms with On Error statements.
Limita ons:
 Limited browser support (primarily works in Internet Explorer).
 Not suitable for complex web applica ons compared to JavaScript.

Q13. Dis nguish Between VBScript and JavaScript


Feature VBScript JavaScript
Developer Microso Netscape
Primary Use Automa ng Windows tasks, basic Client-side scrip ng for web
scrip ng in IE browsers
Syntax Similar to Visual Basic C-like syntax
Browser Works only in Internet Explorer Supported by all major browsers
Support
Execu on Requires Windows Script Host Runs in browsers or Node.js
(WSH) or IE
Data Types Limited data types (e.g., Variant) Mul ple data types (e.g., String,
Number, Object)
Event Basic support Extensive event handling
Handling
Func ons Limited built-in func ons Rich set of built-in func ons
Usage Today Declining, mostly obsolete Widely used for web development

Q14. Explain Various Data Types Available in VBScript


VBScript has a simplified approach to data types. It uses the Variant type to represent all
data, but it can store values of different subtypes.
Common Subtypes in VBScript:
1. Numeric Subtypes:
o Integer: Stores whole numbers.
Dim num
num = 10
o Double: Stores decimal numbers.
Dim price
price = 19.99
2. String:
o Represents a sequence of characters.
Dim name
name = "Alice"
3. Boolean:
o Stores True or False.
Dim isAvailable
isAvailable = True
4. Date:
o Stores date and me values.
Dim currentDate
currentDate = Now
5. Empty:
o Represents an unini alized variable.
6. Null:
o Represents a variable with no valid data.
Type Conversion:
 VBScript provides func ons like CInt, CDbl, and CStr to convert data types.

Q15. What Are Variables and Constants in VBScript?


Variables:
Variables in VBScript are placeholders for storing data that can change during program
execu on.
 Declaring a Variable:
o Use Dim, Public, or Private keywords.
Dim age
age = 25
 Rules:
o Variable names must begin with a le er.
o Cannot exceed 255 characters.
o Cannot use reserved keywords.
Constants:
Constants are named values that do not change during execu on.
 Declaring a Constant:
o Use the Const keyword.
Const Pi = 3.14
 Example:
Const MaxA empts = 5
Dim a empts
a empts = 3
If a empts < MaxA empts Then
MsgBox "You can try again."
End If

Q16. Explain Various Types of Operators in VBScript


Operators in VBScript are symbols or keywords used to perform opera ons on variables or
values. These opera ons can include arithme c, comparison, logical, and more.
Types of Operators:
1. Arithme c Operators:
o Used for mathema cal calcula ons.
o Examples:
Dim x, y, result
x = 10
y=5
result = x + y ' Addi on
result = x - y ' Subtrac on
result = x * y ' Mul plica on
result = x / y ' Division
result = x Mod y ' Modulus (remainder)
2. Comparison Operators:
o Compare two values and return True or False.
o Examples:
Dim a, b
a = 15
b = 10
If a > b Then MsgBox "a is greater than b" ' Greater than
If a < b Then MsgBox "a is less than b" ' Less than
If a = b Then MsgBox "a equals b" ' Equality
If a <> b Then MsgBox "a is not equal to b" ' Not equal
3. Logical Operators:
o Combine mul ple condi ons.
o Examples:
Dim age
age = 20
If age >= 18 And age <= 25 Then
MsgBox "You are eligible."
End If
4. Concatena on Operator:
o Joins two strings.
o Example:
Dim firstName, lastName, fullName
firstName = "John"
lastName = "Doe"
fullName = firstName & " " & lastName
MsgBox fullName
5. Assignment Operator:
o Assigns a value to a variable.
o Example:
Dim score
score = 100
6. Bitwise Operators:
o Perform bitwise opera ons.
o Example:
Dim num1, num2, result
num1 = 5 ' Binary: 0101
num2 = 3 ' Binary: 0011
result = num1 And num2 ' Result: 1 (Binary: 0001)

Q17. Explain MsgBox Func on and InputBox Func on by Using Examples


MsgBox Func on:
The MsgBox func on displays a message box to the user and can return a value based on
user interac on.
 Syntax:
MsgBox(prompt[, bu ons][, tle])
 Parameters:
o prompt: The message to display.
o bu ons: The type of bu ons and icons to show (op onal).
o tle: The tle of the message box (op onal).
 Example:
Dim response
response = MsgBox("Do you want to save changes?", vbYesNoCancel, "Save Changes")
If response = vbYes Then
MsgBox "Changes saved!"
ElseIf response = vbNo Then
MsgBox "Changes discarded!"
Else
MsgBox "Opera on canceled."
End If
InputBox Func on:
The InputBox func on displays a dialog box that prompts the user for input.
 Syntax:
InputBox(prompt[, tle][, default])
 Parameters:
o prompt: The message to display.
o tle: The tle of the input box (op onal).
o default: A default value for the input field (op onal).
 Example:
Dim userName
userName = InputBox("Enter your name:", "User Name", "John Doe")
MsgBox "Hello, " & userName

Q18. Explain the Decision Statements in VBScript by Using Examples


Decision statements in VBScript control the flow of the program based on condi ons.
Types of Decision Statements:
1. If...Then Statement:
o Executes code if a condi on is True.
o Example:
Dim score
score = 80
If score >= 50 Then
MsgBox "You passed!"
End If
2. If...Then...Else Statement:
o Provides an alterna ve block of code if the condi on is False.
o Example:
Dim age
age = 17
If age >= 18 Then
MsgBox "You are eligible to vote."
Else
MsgBox "You are not eligible to vote."
End If
3. If...Then...ElseIf Statement:
o Handles mul ple condi ons.
o Example:
Dim marks
marks = 85
If marks >= 90 Then
MsgBox "Grade: A"
ElseIf marks >= 75 Then
MsgBox "Grade: B"
Else
MsgBox "Grade: C"
End If
4. Select Case Statement:
o Evaluates a single expression and executes code based on matching cases.
o Example:
Dim day
day = "Monday"
Select Case day
Case "Monday"
MsgBox "Start of the week!"
Case "Friday"
MsgBox "Almost weekend!"
Case Else
MsgBox "Have a great day!"
End Select
Q19. Explain the Loop Statements in VBScript by Using Examples
Loop statements in VBScript are used to execute a block of code repeatedly, either for a
specific number of itera ons or un l a condi on is met.
Types of Loop Statements:
1. For...Next Loop:
o Repeats a block of code a specified number of mes.
o Syntax:
For counter = start To end [Step step]
' Code to execute
Next
o Example:
Dim i
For i = 1 To 5
MsgBox "Itera on: " & i
Next
2. For Each...Next Loop:
o Iterates through each item in a collec on or array.
o Example:
Dim fruits, fruit
fruits = Array("Apple", "Banana", "Cherry")
For Each fruit In fruits
MsgBox "Fruit: " & fruit
Next
3. Do While Loop:
o Executes the block of code as long as the condi on is True.
o Syntax:
Do While condi on
' Code to execute
Loop
o Example:
Dim x
x=1
Do While x <= 5
MsgBox "Value: " & x
x=x+1
Loop
4. Do Un l Loop:
o Executes the block of code un l the condi on becomes True.
o Syntax:
Do Un l condi on
' Code to execute
Loop
o Example:
Dim y
y=1
Do Un l y > 5
MsgBox "Value: " & y
y=y+1
Loop
5. While...Wend Loop:
o Similar to Do While, but uses Wend instead of Loop.
o Example:
Dim z
z=1
While z <= 3
MsgBox "Count: " & z
z=z+1
Wend

Q20. Explain User-Defined Func ons in VBScript by Using Examples


User-defined func ons in VBScript are reusable blocks of code created by the programmer
to perform specific tasks. These func ons make code modular and reduce redundancy.
Crea ng a Func on:
 Syntax:
Func on Func onName(parameters)
' Code to execute
Func onName = return_value
End Func on
Example 1: Func on with Parameters and Return Value
Func on AddNumbers(a, b)
AddNumbers = a + b
End Func on

Dim result
result = AddNumbers(5, 10)
MsgBox "Sum: " & result
Example 2: Func on Without Parameters
vbscript
CopyEdit
Func on GetGree ng()
GetGree ng = "Hello, welcome to VBScript!"
End Func on
Dim message
message = GetGree ng()
MsgBox message
Advantages of Func ons:
 Reusability: Func ons can be called mul ple mes.
 Modularity: Code is easier to maintain and debug.
 Flexibility: Func ons can accept parameters to process different data.

Q21. Explain Subrou ne Procedure in VBScript by Using Examples


Subrou nes in VBScript are similar to func ons but do not return a value. They perform a
task when called.
Crea ng a Subrou ne:
 Syntax:
Sub SubName(parameters)
' Code to execute
End Sub
Example 1: Subrou ne with Parameters
Sub DisplayMessage(message)
MsgBox "Message: " & message
End Sub

Call DisplayMessage("Hello, VBScript!")


Example 2: Subrou ne Without Parameters
Sub ShowAlert()
MsgBox "This is a subrou ne example."
End Sub

Call ShowAlert()
Differences Between Subrou nes and Func ons:
Feature Subrou ne Func on
Return No Yes
Value
Syntax Sub...End Sub Func on...End Func on
Usage Perform tasks without returning a Perform tasks and return a
value value

Q22. What is a String? Explain Various Func ons of String


A string in VBScript is a sequence of characters enclosed within double quotes. Strings are
commonly used to store and manipulate text.
String Func ons:
1. Len:
o Returns the length of a string.
o Example:
Dim text
text = "Hello"
MsgBox "Length: " & Len(text) ' Output: 5
2. Mid:
o Extracts a substring from a string.
o Example:
Dim text
text = "Welcome"
MsgBox Mid(text, 2, 3) ' Output: "elc"
3. Le :
o Extracts a specified number of characters from the start.
o Example:
MsgBox Le ("VBScript", 2) ' Output: "VB"
4. Right:
o Extracts a specified number of characters from the end.
o Example:
MsgBox Right("VBScript", 3) ' Output: "ipt"
5. Instr:
o Finds the posi on of a substring in a string.
o Example:
MsgBox Instr("VBScript", "Script") ' Output: 3
6. Replace:
o Replaces occurrences of a substring.
o Example:
MsgBox Replace("I love VBScript", "love", "like") ' Output: "I like VBScript"
7. UCase and LCase:
o Converts a string to uppercase or lowercase.
o Example:
MsgBox UCase("hello") ' Output: "HELLO"
MsgBox LCase("HELLO") ' Output: "hello"

Q23. Explain Various Func ons of Dates and Times by Using Examples
VBScript provides several built-in func ons to handle date and me opera ons. These
func ons allow developers to retrieve, manipulate, and format date and me values
efficiently.
Common Date and Time Func ons:
1. Now:
o Returns the current date and me.
o Example:
MsgBox "Current Date and Time: " & Now
2. Date:
o Returns the current date without the me.
o Example:
MsgBox "Today's Date: " & Date
3. Time:
o Returns the current me without the date.
o Example:
MsgBox "Current Time: " & Time
4. Day, Month, Year:
o Extracts the day, month, or year from a date.
o Example:
Dim currentDate
currentDate = Date
MsgBox "Day: " & Day(currentDate)
MsgBox "Month: " & Month(currentDate)
MsgBox "Year: " & Year(currentDate)
5. DateAdd:
o Adds a specified me interval to a date.
o Example:
Dim futureDate
futureDate = DateAdd("d", 5, Date) ' Adds 5 days to today's date
MsgBox "Future Date: " & futureDate
6. DateDiff:
o Calculates the difference between two dates.
o Example:
Dim diff
diff = DateDiff("d", "01/01/2023", "01/15/2023") ' Difference in days
MsgBox "Days Difference: " & diff
7. Weekday:
o Returns the day of the week for a given date (as a number, 1=Sunday to
7=Saturday).
o Example:
MsgBox "Day of the Week: " & Weekday(Date)
8. FormatDateTime:
o Formats a date/ me value based on a specific format.
o Example:
Dim forma edDate
forma edDate = FormatDateTime(Now, vbLongDate)
MsgBox "Forma ed Date: " & forma edDate
Common Date and Time Format Constants:
 vbGeneralDate: Default format for date and me.
 vbLongDate: Long date format.
 vbShortDate: Short date format.
 vbLongTime: Long me format.
 vbShortTime: Short me format.
Usage Example:
Dim currentDate, forma edTime
currentDate = Now
forma edTime = FormatDateTime(currentDate, vbLongTime)
MsgBox "Full Date: " & currentDate & vbCrLf & "Forma ed Time: " & forma edTime

Q24. Write a Short Note on Event Handling in VBScript


Event handling in VBScript refers to the process of execu ng code in response to specific
ac ons or events performed by the user or system. Events can include ac ons like clicking
a bu on, loading a webpage, or changing a value in a form field.
Common Events in VBScript:
1. OnClick:
o Triggered when an element (like a bu on) is clicked.
o Example:
<html>
<body>
<bu on onclick="MsgBox 'Bu on Clicked!'">Click Me</bu on>
</body>
</html>
2. OnLoad:
o Triggered when a webpage or an element finishes loading.
o Example:
<html>
<body onload="MsgBox 'Page Loaded!'">
Welcome to the page.
</body>
</html>
3. OnChange:
o Triggered when the value of an input field changes.
o Example:
<html>
<body>
<input type="text" onchange="MsgBox 'Text Changed!'">
</body>
</html>
4. OnMouseOver and OnMouseOut:
o Triggered when the mouse pointer moves over or out of an element.
o Example:
<html>
<body>
<bu on onmouseover="MsgBox 'Mouse Over!'" onmouseout="MsgBox 'Mouse
Out!'">Hover Over Me</bu on>
How Event Handling Works:
 VBScript allows developers to write scripts that respond to events using the
EventName a ribute in HTML elements.
 Event handlers can execute VBScript code or call a predefined subrou ne.
Advantages of Event Handling:
 Enhances interac vity and user experience.
 Allows dynamic responses to user ac ons.
Example: A Simple Event Script
<html>
<body>
<bu on onclick="MsgBox 'Hello, VBScript Event Handling!'">Click Me</bu on>
</body>
</html>
Event handling in VBScript is essen al for crea ng dynamic and interac ve webpages,
enabling developers to react to user behavior seamlessly.

You might also like