0% found this document useful (0 votes)
26 views240 pages

JavaScript Functions & Objects Guide

Uploaded by

dynamogamer911
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)
26 views240 pages

JavaScript Functions & Objects Guide

Uploaded by

dynamogamer911
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

SAVITRIBAI PHULE PUNE UNIVERSITY

B.E. (Department of ENTC)


2019 Pattern

(Elective- III)

Javascript

- Complete Notes -
For End-Sem Examination
( Covered All the previous year Question and some
expected question )

DESIGNED BY
Professors At Top Ranked Institute In SPPU
Unit-3: Functions & Objects

Expected Questions :
-> What is function? Explain with example how to pass and return parameters
and arguments from called function to the calling function.
-> What are Common properties and methods of object in JavaScript?
-> Write a JavaScript program to pass the function by reference, perform
addition of two objects inside the function and display the result in calling
function.
-> What is Anonymous Functions in JavaScript? Explain its use with an example.
-> Write a JavaScript program that will append an object to an array and will
check if an object is an array data types.
-> Explain data types in JavaScript? Differentiate between primitive and non-
primitive.
-> Explain the Mask out with respect to functions in Java Script.
-> Explain how function is used as object in Java Script.
-> How Arrays can be used as Stacks and Queues in Java Script.
-> Explain different types of Objects.
-> List the various methods of Math object. Explain any one with example.
Expected Question :
-> a) What is function? Explain with example how to pass and return
parameters and arguments from called function to the calling function

Functions
- Functions in JavaScript are reusable code blocks used to perform specific
tasks multiple times.
- Functions should ideally be self-contained, with clear input (parameters) and
output.
- JavaScript allows modular code through functions and supports advanced
features like variable parameter lists.
- Function names should follow the same rules as variable names, and descriptive
names are recommended to reflect the function’s purpose.

- The syntax to define a function is as follows:

function functionName(parameter-list) {
// statements
}

- The function body is written inside curly braces ‘{}’.


- Functions do not allow forward references to parameters.

Calling a Function
- A function must be defined before calling it unless it is defined in a ‘<script>‘
tag, where forward references can be made.

Parameter Passing
- Parameters are data sent to a function to perform operations, while arguments
are the values provided when the function is called.
- JavaScript does not require a data type while defining parameters.
- If a parameter is defined without an argument being passed, its value will be
‘undefined’.
- Example of a simple function with a parameter:
function sayHello(name) {
if (name != "")
alert("Hello " + name);
else
alert("Don't be shy");
}
sayHello("George"); // This will show: Hello George

- A function can also take multiple parameters. For example:


function addThree(arg1, arg2, arg3) {
alert(arg1 + arg2 + arg3);
}
var x = 5, y = 7;
addThree(x, y, 11); // This will show: 23

- Arguments can be literal values, variables, or a combination of both.

Care with Parameter Passing


- JavaScript is weakly typed, so unexpected results may occur.
- Example:
addThree(5, 11, "Watch Out!"); // This will show: 16Watch Out!

Parameter Passing: In and Out

Primitive Data Types: Pass-By-Value


- Primitive data types in JavaScript are passed by value, meaning a copy of the
variable is passed to the function.
- Any changes made to the parameter inside the function do not affect the
original variable.
- Example:
function fiddle(arg1) {
arg1 = 10;
[Link]("In function fiddle, arg1 = " + arg1 + "<br />");
}
var x = 5;
[Link]("Before function call, x = " + x + "<br />"); // 5
fiddle(x);
[Link]("After function call, x = " + x + "<br />"); // 5

- Here, the function modifies ‘arg1’ but does not affect the original value of ‘x’
since it works with a copy.

Composite Types: Pass-By-Reference


- Composite types like arrays and objects are passed by reference.
- When a reference type is passed, the function gets access to the original data,
not a copy.
- Changes made to the parameter inside the function will directly affect the
original value.
- Example:
function fiddle(arg1) {
arg1[0] = "changed";
[Link]("In function fiddle, arg1 = " + arg1 + "<br />");
}
var x = ["first", "second", "third"];
[Link]("Before function call, x = " + x + "<br />"); // first, second, third
fiddle(x);
[Link]("After function call, x = " + x + "<br />"); // changed, second,
third

- Here, the original array ‘x’ is modified because the function operates on its
reference.

Return Statement in Functions


- Functions often process input and generate a result, which can be returned
using the ‘return’ statement.
- The ‘return’ statement stops the function’s execution and outputs a value.
- You can return primitive values (e.g., numbers, strings) or object types (e.g.,
arrays, objects).

- Example:
function addThree(arg1, arg2, arg3) {
return arg1 + arg2 + arg3;
}
var x = 5, y = 7;
var result = addThree(x, y, 11); // result = 23
- If no ‘return’ statement is included, the function returns ‘undefined’ by default.

Global Variables
- Global variables are defined outside functions and are accessible throughout
the document.
- Multiple functions can access and modify global variables.
- Example:
var x = 5; // Global variable
function myFunction() {
[Link]("Entering function<br>");
[Link]("x = " + x + "<br>"); // x = 5
x = 7; // Modify global variable
[Link]("x = " + x + "<br>"); // x = 7
[Link]("Leaving function<br>");
}
[Link]("Starting Script<br>");
[Link]("x = " + x + "<br>"); // x = 5
myFunction();
[Link]("x = " + x + "<br>"); // x = 7
[Link]("Ending Script<br>");

- Modifying a global variable within a function changes its value for the entire
script.
- Global variables reduce reusability and increase complexity in scripts.
- Variables declared without the ‘var’, ‘let’, or ‘const’ keyword automatically
become global.

- Example:
function greet() {
a = "hello"; // ‘a’ becomes global
}
greet();
[Link](a); // hello

- Avoid using global variables wherever possible to maintain code reusability and
simplicity.

Local Variables
- A local variable is one that is defined within a specific block of code and can
only be accessed within that block.
- The scope of a local variable is restricted to the block of code (denoted by ‘{}’)
in which it is declared.
- Local variables are created to encapsulate functionality and hide the
implementation details of a function.

- Example:
function myFunction() {
var y = 5; // local variable
[Link]("Within function, y = " + y + "<br>");
}
myFunction();
[Link]("After function, y = " + y + "<br>"); // undefined

- In this example, the variable ‘y’ is only accessible within ‘myFunction’. Outside
of the function, trying to access ‘y’ results in ‘undefined’.
- Local variables help in creating functions that can be reused without exposing
their internal implementation.

Expected Question :
a) Explain the Mask out with respect to functions in Java Script.

Mask Out :
- When both local and global variables have the same name, the local variable
takes precedence over the global one inside the function. This is known as "mask
out".
- Example:
var x = "As global I am a string"; // Global variable
function maskDemo() {
var x = 5; // Local variable with the same name as global variable
[Link]("In function, x = " + x + "<br>"); // 5

}
[Link]("Before function call, x = " + x + "<br>"); // As global I am a
string
maskDemo();
[Link]("After function call, x = " + x + "<br>"); // As global I am a string

- Here, the local variable ‘x’ inside ‘maskDemo’ "masks out" the global ‘x’ within
the function, and the value of global ‘x’ remains unchanged after the function
call.
- To avoid confusion and conflicts, it’s a good practice to use unique variable
names, especially when reusing scripts.

Local Functions
- A local function is defined inside another function. These functions are also
known as inner functions or nested functions.
- Functions in JavaScript are treated as objects, and this allows them to be
defined within other functions.
- Local functions can only be called within the function in which they are
declared.
- Example:
function testFunction() {
function inner1() {
[Link]("testFunction-inner1 <br>");
}
function inner2() {
[Link]("testFunction-inner2 <br>");
}
[Link]("Entering testFunction <br>");
inner1();
[Link]("Leaving testFunction <br>");
inner2();
}
[Link]("About to call testFunction <br>");
testFunction();

[Link]("Returned from testFunction <br>");

- In this example, the functions ‘inner1’ and ‘inner2’ are defined inside
‘testFunction’ and can only be called within ‘testFunction’.
- Attempting to call ‘inner1()’ or ‘inner2()’ outside of ‘testFunction’ will result in
an error.
- Local functions provide a way to organize code into self-contained blocks,
allowing for modular development.
- Local or nested functions have been supported in browsers since the 4.x
generation.
Expected Question :
b) Explain how function is used as object in Java Script.

Functions as Objects
- In JavaScript, functions are treated as objects.
- This means that, like other objects, functions can be assigned to variables,
passed as arguments, and returned from other functions.
- Functions can also be created using the ‘Function’ constructor.

Syntax
var functionName = new Function("argument1", "argument2", "body of function");

- The ‘Function’ constructor expects a variable number of string arguments. The


last argument is the body of the function, containing JavaScript statements.
- A function defined using the ‘Function()’ constructor does not require a name;
the name is set by the variable name.

Example with arguments


var sayHello2 = new Function("msg", "alert('Hello there ' + msg);");
sayHello2('Thomas');

Example without arguments


var sayHello = new Function("alert('Hello there');");
sayHello();

Reusing Functions
Functions can be assigned to other variables, allowing them to be reused or called
with different names.
var sayHelloAgain = sayHello;
sayHelloAgain();

- The key advantage of using the ‘Function()’ constructor is that it allows the
creation of functions dynamically, even after the page is loaded.
Expected Question :
a) What is Anonymous Functions in JavaScript? Explain its use with an
example.

Function Literals & Anonymous Functions


- A function literal defines an unnamed function, and this type of function is
also referred to as an anonymous function.

Syntax
var variablename = function(argumentList) {
// Function body
};

- In this case, the function does not have a name, but it can be assigned to a
variable or passed as an argument.

Example of anonymous function


var multiply = function(x, y) {
return x * y;
};
alert(multiply(2, 3)); // 6

- Anonymous functions are often used where a function is only needed


temporarily, such as when sorting an array or in event handling.

Example with sorting


var myArray = [2, 4, 2, 17, 50, 8];
[Link](function(x, y) {
return x - y;
});

- Example of anonymous function with event handler :


<!DOCTYPE html>
<html>
<head><title>Simple Event and Anonymous Functions</title></head>
<body>
<input type="button" id="button" value="Press me">
<script type="text/javascript">
[Link]("button").onclick = function() {
alert('Button pressed!');
};
</script>
</body>
</html>

Arrow Functions
- Arrow functions, introduced in ES6, offer a more concise syntax for writing
functions.
- They use the ‘=>‘ syntax and do not require the ‘function’ keyword. However,
arrow functions have some differences compared to traditional functions:
- They do not have their own ‘this’ context, but inherit it from the surrounding
code.
- They cannot be used as constructors (i.e., with the ‘new’ keyword).
- They are always anonymous.

Example of arrow function


var hello = (name) => {
return "Hello " + name;
};
alert(hello("World")); // "Hello World"

- Arrow functions provide a more concise way to write functions, especially when
they are used as callbacks or in simple operations.
Static Variables :
- In JavaScript, we can create static variables within a function.
- These are variables that persist across function invocations, meaning their
value is retained between calls.
- Static variables are typically created by adding an instance property to the
function.
- The value of a static variable is shared across all invocations of the function,
and it doesn't get reinitialized each time the function is called.

- Example of Static Variable in a Function

function doSum(x, y) {
[Link] = [Link] || 0; // Define a static variable
[Link] += (x + y); // Update running sum
return [Link]; // Return the current sum
}
[Link]("First Call: " + doSum(5, 10) + "<br />"); // 15
[Link]("Second Call: " + doSum(5, 10) + "<br />"); // 38
[Link]("Third Call: " + doSum(100, 100) + "<br />"); // 230

- In the above example, ‘[Link]’ acts as a static variable that retains


its value between function calls.
- It avoids the need for global variables and maintains state across invocations.

Example of Static Variable in a Class


class Example {
static staticVariable = "Welcome to Arrow Functions"; // Static variable
static staticMethod() {
return "I am a static method."; // Static method
}
}
[Link]([Link]); // Accessing static variable
[Link]([Link]()); // Accessing static method
- Static variables in classes are shared across all instances of the class and can
be accessed using the class name directly.

Advanced Parameter Passing


- JavaScript is a weakly typed language, meaning we can define functions that
do not specify their number of arguments.
- The number of arguments passed to a function can vary, and JavaScript
functions handle this flexibility using the ‘arguments[]’ array.
- ’[Link]’ provides the number of arguments passed during a function
call.
- The ‘arguments[]’ array holds the actual values passed to the function, which
can be accessed by index.

Example - ‘length’ Property


function myFunction(arg1, arg2, arg3) {
alert("Number of parameters expected for myFunction: " +
[Link]);
}
myFunction(1, 2, 3); // 3

- Here, the function ‘myFunction’ expects 3 parameters, and the ‘length’


property will return ‘3’.

Example - Using ‘arguments[]’ Array


function myFunction() {
[Link]("Number of parameters defined: " + [Link] +
"<br>");
[Link]("Number of parameters passed: " + [Link] +
"<br>");
for (var i = 0; i < [Link]; i++) {
[Link]("Parameter " + (i+1) + ": " + arguments[i] + "<br>");
}
}
myFunction(33, 858, 404);

Output:
Number of parameters defined: 0
Number of parameters passed: 3
Parameter 1: 33
Parameter 2: 858
Parameter 3: 404

- In this example, even though the function doesn't define any parameters, the
‘arguments[]’ array captures the passed arguments.

- Example - Summation Routine


function sumAll() {
var total = 0;
for (var i = 0; i < [Link]; i++) {
total += arguments[i];
}
return total;
}

alert(sumAll(3, 5, 3, 5, 3, 2, 6)); // 27

- In this example, ‘sumAll’ adds all the numbers passed to it, regardless of how
many parameters are provided.
- This function works best when only numbers are passed; passing strings would
lead to unexpected results.
- By using the ‘arguments[]’ array, we can handle a flexible number of parameters
without needing to predefine them.

Recursive Functions
- A recursive function is a function that calls itself in order to solve a problem.
- This approach is often used when a problem can be divided into smaller
subproblems of the same type.
- While recursion can lead to elegant solutions, it may not always be the most
efficient, especially in terms of execution time due to the overhead of repeated
function calls.

Factorial Example
- A common example of recursion is calculating the factorial of a number,
defined mathematically as:

- ‘factorial(n) = n * (n - 1) * (n - 2) * ... * 1’
- ‘factorial(0) = 1’

- This is the definition of the factorial function, and a recursive implementation


can be written as follows:

function factorial(n) {
if (n === 0) {
return 1; // Base case
} else {
return n * factorial(n - 1); // Recursive case
}
}

alert(factorial(5)); // 120

- In this example, the function ‘factorial’ keeps calling itself with smaller values
of ‘n’ until it reaches the base case (‘n === 0’).
- If a negative value is passed, the function would result in a Stack Overflow
error due to the infinite recursion.

Tips for Good Programming Practices

1. Define All Functions First


- It's a good practice to define all functions in your script before calling them.
- This helps in maintaining and debugging your code since the browser will read
all functions before they are invoked.

2. Name Functions Well


- Avoid naming functions and variables the same to prevent name conflicts.
- This can lead to subtle bugs and make your code harder to debug.
- Consider using a prefix like ‘func_’ to distinguish functions from variables.

var x = 5; // Variable
function x() { // Function
alert("I'm a function!");
}
alert(typeof x); // number

- In this case, there could be confusion, as the variable ‘x’ might override the
function ‘x’.

3. Consider Using Linked JavaScript Files


- When working with external JavaScript files, ensure that functions are
available before being invoked.
- If two scripts rely on each other, the load order matters. For instance:

var lib1Loaded = false;


var lib2Loaded = false;
if (lib1Loaded) {
doSomething(x, y, z);
}
- Make sure to load scripts in the correct order to avoid issues where one script
depends on another.

4. Use Explicit Return Statements


- Even if a function does not need to return any value, explicitly use a ‘return’
statement.
- This helps the JavaScript interpreter optimize execution and can prevent
unexpected behavior.

function noReturn() {
alert("This function does not return anything.");
return; // Explicit return
}

5. Write Stand-Alone Functions


- Follow modular design principles and ensure functions are stand-alone.
- They should only rely on their arguments and return values, avoiding side
effects like modifying global variables.
- This makes functions reusable and easier to test.

For example:

function calculateSum(a, b) {
return a + b; // Stand-alone function
}

let sum = calculateSum(5, 3);

- By following these practices, your code will be more maintainable, modular, and
less prone to bugs.

Check Arguments Carefully


- In JavaScript, functions do not automatically check the number or type of
arguments passed.
- This flexibility can be powerful when writing functions that accept a variable
number of arguments (variadic functions), but it can also lead to unexpected
behavior if not handled properly.
For instance, consider this simple function:

function addTwoNumbers(x, y) {
alert(x + y);
}
addTwoNumbers(5); // Undefined behavior

- In the example above, since the function ‘addTwoNumbers’ expects two


arguments but only one is provided, it will produce an ‘undefined’ result for ‘y’.
- This can be fixed by checking the number of arguments passed:

function addTwo(x, y) {
if ([Link] == 2) {
alert(x + y);
} else {
alert("Two arguments are required.");
}
}

- In this revised version, the function checks if exactly two arguments were
provided before performing the addition.
- If fewer arguments are passed, it will show a message indicating that two
arguments are needed.

Handling Types Carefully


- In addition to checking the number of arguments, checking the types of the
arguments can prevent problems like unexpected results.

For example:
function addTwo(x, y) {
if ([Link] == 2) {
if (typeof(x) !== "number" || typeof(y) !== "number") {
alert("Both arguments must be numbers.");
return;
}
alert(x + y);
} else {
alert("Two arguments are required.");
}
}

- Here, the function checks both the number of arguments and their types,
ensuring that both ‘x’ and ‘y’ are numbers before performing the addition.

Comment Functions
- Good programming practices involve documenting your functions to describe
their purpose, inputs, outputs, and any side effects.
- A well-commented function helps other developers (or even yourself)
understand the code easily.

Here’s an example of a comment block before a function:

/*
Function: customAlert
Description: Creates a custom alert dialog with a message, icon, background
color, and button text.
Input:
- message: A string containing the message to be displayed.
- icon: Reference to a GIF or JPEG image to be used in the dialog.
- color: The background color in hexadecimal. Defaults to white if unspecified.
- buttontext: The text for the button. Defaults to "ok" if unspecified.

Output: Creates a dialog window and returns true if successful, false otherwise.
*/

function customAlert(message, icon, color, buttontext) {


// Function logic here
}

This comment block explains:


- The function's purpose.
- The types and descriptions of its parameters.
- The output the function generates.

- Such comments improve the maintainability of your code and ensure that other
developers can easily use or modify the function.

Objects in JavaScript

Expected Question :
1) Explain different types of Objects.

- In JavaScript, an object is an entity that has a state (attributes or properties)


and behavior (methods).
- These attributes can be either simple data types or more complex structures
like other objects.
- Objects are essential for grouping related data and functionality into a single
container, making the code more structured and manageable.
- Objects can store data and logic, bringing both the state (variables) and
behavior (functions) together.
- For example, if an object has a property that is a function, that function is
considered a method of the object, whereas if it is a non-function property, it
is considered a property of the object.

Types of Objects
- Objects in JavaScript fall into four main categories:

1. User-defined Objects
- These are objects created by the programmer to bring structure and
consistency to a particular task. They can be created in three ways:

Object Literal
This is the simplest way to create an object by directly defining properties
and values.
var emp = {
id: 102,
name: "Sunil Kumar",
salary: 40000
};

Using the ‘new Object()’ Syntax


Another way is by creating an empty object and assigning properties to it.

var emp = new Object();


[Link] = 101;
[Link] = "Ravi Malik";
[Link] = 50000;

Using a Constructor Function


A constructor function allows you to define an object template and instantiate
multiple objects with similar properties.

function Employee(id, name, salary) {


[Link] = id;
[Link] = name;
[Link] = salary;
}

var emp1 = new Employee(101, "Ravi Malik", 50000);


var emp2 = new Employee(102, "Vimal Jadhav", 30000);
2. Built-in Objects
- These objects are provided by JavaScript and are part of the language itself.
They include:

Data Type Objects: ‘String’, ‘Number’, and ‘Boolean’ which encapsulate primitive
data types.

Composite Objects: ‘Object’ and ‘Array’ used for more complex data structures.

Utility Objects: ‘Date’, ‘Math’, and ‘RegExp’ are built to simplify common tasks
like handling dates, performing mathematical calculations, and working with
regular expressions.

- Each built-in object comes with predefined methods and properties that
simplify programming.

3. Browser Objects
- These objects are not part of JavaScript itself but are typically supported by
most browsers. Examples include:

- Window Object: Provides methods and properties to interact with the


browser window.
- Navigator Object: Provides information about the browser and the user's
environment.

- Browser objects are not standardized and their behavior might differ across
different browsers and versions.

4. Document Objects (DOM)


- These objects are part of the Document Object Model (DOM), which is a W3C
specification that allows JavaScript to interact with HTML and XML documents.
- Through the DOM, JavaScript can manipulate the structure of the document,
access elements, and modify them dynamically.
- Some important properties and methods of the document object include:
- ‘[Link]()’: Returns a reference to an element by its ID.
- ‘[Link]()’: Returns a collection of elements with
a specific class name.
- ‘[Link]()’: Creates a new element node.

- The DOM enables JavaScript to dynamically update content on web pages,


which is a core concept behind Dynamic HTML (DHTML).

Object Destruction and Garbage Collection in JavaScript


- In JavaScript, memory management is automatic, meaning programmers don’t
need to worry about manually allocating or deallocating memory.
- However, objects and variables do consume memory, and when they are no
longer needed, JavaScript's garbage collection mechanism automatically frees
up memory.

Garbage Collection
- Garbage collection is the process by which JavaScript automatically manages
memory.
- When an object or variable is no longer accessible (for instance, when it goes
out of scope), the JavaScript engine marks that object as eligible for garbage
collection, which means the memory occupied by that object will be returned to
the pool of available memory for future use.
- This feature prevents memory leaks and ensures efficient memory usage
without manual intervention.

Example:

let obj = { name: "John", age: 30 };


// obj is accessible here

obj = null; // Now the object is eligible for garbage collection because it's no
longer referenced
- JavaScript automatically takes care of cleaning up the memory when objects
are no longer needed.

Enumerating Properties of an Object


- JavaScript provides a convenient way to iterate over an object's properties
using a ‘for-in’ loop.
- This loop allows you to access each property of an object, one at a time.

Syntax:

for (let variable in object) {


// code to be executed
}

- This loop works by iterating over the names of properties in an object.


- During each iteration, the ‘variable’ will hold the name of the current property,
and you can use it to access the value of that property.

Example:
var person = {
firstName: "John",
lastName: "Doe",
age: 25
};
for (let prop in person) {
[Link]("Property: " + prop + ", Value: " + person[prop]);
}

This will output:


Property: firstName, Value: John
Property: lastName, Value: Doe
Property: age, Value: 25
Objects are Reference Types
- JavaScript data types can be categorized as primitive or reference types:

- Primitive types: These include ‘number’, ‘string’, ‘boolean’, ‘undefined’, and ‘null’.
They hold the actual value directly.
- Reference types: These include objects, arrays, and functions. Instead of
holding the actual value, a reference type variable holds a reference to the
memory location where the actual data is stored.

Example with Primitive Types:


var x = 10;
var y = x; // y gets a copy of x's value
x = 2;
alert("The value of y is: " + y); // Output: 10, because y got a copy of x's value
at the time of assignment

- In the above example, since ‘x’ is a primitive type (‘number’), when ‘y’ is assigned
‘x’, a copy of ‘x’'s value is made. Changing the value of ‘x’ later doesn't affect ‘y’.

Example with Reference Types:

var x = [10, 9, 8]; // x is an array


x[0] = 2;
var y = x; // y now holds a reference to the same array as x
alert("The value of y's first element is: " + y[0]); // Output: 2, because y refers
to the same array as x

- In this case, both ‘x’ and ‘y’ point to the same array in memory.
- Modifying the array through either variable will be reflected in the other,
since they both reference the same object.
Passing Objects to Functions in JavaScript
- In JavaScript, we can pass objects to functions just like other data types.
- However, there are important differences between how primitive types and
reference types behave when passed to functions.

Passing Primitive Types:


- Primitive types (like ‘number’, ‘string’, ‘boolean’) are passed by value.
- This means that when you pass a primitive type to a function, a copy of the
value is passed.
- Any changes made to the parameter inside the function do not affect the
original variable.

Passing Objects:
- Objects, on the other hand, are reference types. When you pass an object to
a function, a reference to the original object is passed.
- This means that the function can modify the original object because both the
original and the copy point to the same memory location.

Example:

var refType = ["first", "second", "third"]; // An array (reference type)


var primType = 10; // A number (primitive type)

function modifyValues(ref, prim) {


ref[0] = "changed"; // Modify the first element of the array
prim = 8; // Modify the primitive variable (this won't affect the original value)
}

modifyValues(refType, primType); // Call the function

[Link]("Value of refType is: " + refType + "<br>"); // Output: changed,


second, third
[Link]("Value of primType is: " + primType); // Output: 10
Output:
Value of refType is: changed, second, third
Value of primType is: 10

Explanation:
- The ’refType’ array is a reference type, so when it's passed to the function,
both the original variable and the function's parameter point to the same array
in memory.
- Therefore, modifying the array inside the function changes the original
‘refType’ variable.
- The ’primType’ is a primitive type, so only a copy of the value is passed to the
function. Modifying ‘prim’ inside the function does not affect the original
‘primType’ variable.

Expected Question :
b) What are Common properties and methods of object in JavaScript?

Common Properties and Methods in JavaScript Objects

- All JavaScript objects share some common properties and methods. These help
when working with objects, both built-in and custom.
Common Properties and Methods :

1. prototype
- This property points to the object from which the object inherits non-
instance properties.

2. constructor
- This refers to the function that created the object.

3. toString()
- Converts the object into a string, with behavior depending on the object.
4. toLocaleString()
- Converts the object into a localized string (depending on locale).

5. valueOf()
- Converts the object into a primitive type, usually a number.

6. hasOwnProperty(prop)
- Returns ‘true’ if the object has the specified property.

7. isPrototypeOf(obj)
- Returns ‘true’ if the object is the prototype of another object.

8. propertyIsEnumerable(prop)
- Returns ‘true’ if the specified property will show up in a ‘for/in’ loop.

Prototype-Based Inheritance
- In JavaScript, objects are prototype-based. This means that each object has
a prototype, which is an object it inherits properties and methods from.
- Every object in JavaScript has a prototype. This prototype is another object
that contains shared data and methods.
- If an object does not have a property, JavaScript will look for that property
in the object's prototype.

How Prototypes Work:


- When you access a property on an object, JavaScript first checks if the
property exists on the object itself.
- If it doesn't, JavaScript looks at the prototype of the object to find the
property.
- This allows all objects of the same type to share the same properties and
methods.
Example 1: Add a New Property to an Object
- You can add new properties to objects by modifying their prototype. For
example, adding a ‘nationality’ property to a ‘Person’ object:
function Person(first, last, age) {
[Link] = first;
[Link] = last;
[Link] = age;
}

[Link] = "Indian";

var person1 = new Person("John", "Doe", 30);


[Link]([Link]); // John
[Link]([Link]); // Indian

Example 2: Add a New Method to an Object

- You can also add new methods to objects by modifying their prototype. For
example, adding a ‘display()’ method to the ‘Person’ object:

function Person(first, last, age) {


[Link] = first;
[Link] = last;
[Link] = age;
}

[Link] = function() {
return [Link] + " " + [Link];
};

var person2 = new Person("Jane", "Smith", 25);


[Link]([Link]()); // Jane Smith

By using prototypes, you can modify objects even after they have been created,
allowing you to extend their functionality as needed.
Constructor in JavaScript
- In JavaScript, object instances are created using constructors.
- A constructor is a special function that prepares new instances of an object
for use.

- Each constructor has an associated prototype that defines the default


properties and methods for all instances of that constructor.
- You can create object instances for both in-built classes and user-defined
classes using constructors.

In-built Classes Example:


var iobj = new String();

User-defined Classes Example:


var uobj = new ClassName();

- When you use a constructor, it is called in conjunction with the new operator.
- JavaScript knows that these functions are constructors because they are
invoked using new.
- It is a common practice to start constructor names with an uppercase letter,
distinguishing them from instance variables, which start with a lowercase letter.
- When the constructor is invoked, JavaScript automatically allocates memory
for the new object and passes a reference to the object within the constructor
using the this keyword.

Constructor Example:

function Person(first, last, age) {


[Link] = first;
[Link] = last;
[Link] = age;
[Link] = function() {
return [Link] + " " + [Link];
}
}
var mySelf = new Person("John", "Doe", 21);
[Link]([Link]());

Common Methods for Objects

toString() Method
- The ‘toString()’ method converts an object into a string representation.
- It is automatically invoked when an object is used in a context that requires a
string.

Syntax:
[Link](radix)

- Here, ‘radix’ is optional and can take values between 2 and 36 (e.g., 2 for binary,
8 for octal).

Example:
let num = 15;
let text = [Link](2); // converts to binary string
[Link](typeof(text)); // string

valueOf() Method
- The ‘valueOf()’ method is used to convert an object to its most appropriate
primitive value, usually a number. It doesn't change the original object.

Example:
var n1 = "1234";
var n2 = [Link]();
[Link](n2); // 1234 (as number)

hasOwnProperty() Method
- The ‘hasOwnProperty()’ method checks if an object has a specific property. It
returns ‘true’ if the property exists on the object itself and not its prototype.

Example:
var movie = {
name: 'Iron Man',
genre: 'Super Hit'
};
[Link]([Link]('name')); // true
[Link]([Link]('type')); // false

- This method ignores inherited properties, making it useful for checking only
the object's own properties.

isPrototypeOf() Method
- The ‘isPrototypeOf()’ method checks if an object is part of another object's
prototype chain.
- It returns ‘true’ if the object exists in the prototype chain of another object.

Example:
class Foo {}
class Bar extends Foo {}
class Baz extends Bar {}

var foo = new Foo(); // foo: Foo --> Object


var bar = new Bar(); // bar: Bar --> Foo --> Object
var baz = new Baz(); // baz: Baz --> Bar --> Foo --> Object

[Link]([Link](baz)); // true
[Link]([Link](bar)); // false

- The method checks the prototype chain of the object and determines if the
prototype object is part of it.
Generic and User-Defined Objects in JavaScript
- In JavaScript, generic objects can be used to create user-defined data types,
which are one of the most powerful tools for writing complex scripts.
- These generic objects can be created using object literals or the object
constructor.
- As with any JavaScript object, properties and methods can be added
dynamically.

Creating Objects Using the Object Constructor


- You can create a generic object using the ‘new Object()’ syntax.

For example:

var robot = new Object();


[Link] = "Zephyr";
[Link] = "Guard";
[Link] = true;
[Link] = function() {
alert("ZAP!");
};

- In this example, an object ‘robot’ is created, and various properties (like ‘name’,
‘model’, ‘hasJetpack’) and a method ‘attack’ are added to it.
- This illustrates one of the most common uses of generic objects: grouping
related data and functions together.

Object Literals
- JavaScript also supports object literals, which is a more compact way to create
objects.
- Object literals are commonly used because they simplify the process of
defining objects with properties and methods.
- The syntax for an object literal is to use curly braces ‘{}’, and inside the braces,
you list property/value pairs separated by commas.
- Each property name is followed by a colon ‘:’ and its corresponding value.

Syntax:
var myObject = {
property1: 'value1',
property2: 'value2',
method1: function() {
// method body
},
method2: function() {
// method body
}
};

Example of Using Object Literals

var robot = {
name: "Zephyr",
model: "Guard",
hasJetpack: true,
attack: function() {
alert("ZAP!");
}
};

- This example creates the same ‘robot’ object using object literal syntax.
- The object has properties such as ‘name’, ‘model’, and ‘hasJetpack’, and a
method ‘attack’ that triggers an alert.

Advantages of Object Literals


- Compact: Object literals provide a more concise syntax compared to the ‘new
Object()’ constructor.
- Clarity: The properties and methods are listed clearly in one place, which makes
the code easier to read.
- Flexibility: You can use variables or even expressions as values for properties
in the object.

Example with Variables and Expressions

var robotName = "Zephyr";


var robot = {
name: robotName,
model: "Guard",
hasJetpack: true,
attack: function() {
alert("ZAP!");
}
};

- You can also use nested objects and properties with null or undefined values in
object literals, which gives you great flexibility when defining complex objects.

Array in JavaScript

Expected Question :
1) How Arrays can be used as Stacks and Queues in Java Script.

- An array is a collection of elements that are stored in a fixed-size sequential


format. These elements can be of the same type or different types.

Declaring Arrays
Arrays can be declared in different ways:
1. Using Array Literal:
var myArray = [2, 4, 6, 8, "ten"];

2. Using the ‘new Array()’ Constructor:


var myArray = new Array();

3. Using ‘new Array(size)’ to create an array of a specific size:


var myArray = new Array(5); // Creates an array of size 5

4. Empty Array:
var myArray = [];

Expected Question :
1) Write a JavaScript program that will append an object to an array and
will check if an object is an array data types.

Array Methods
- JavaScript arrays have many built-in methods to perform operations on them.
Here are some commonly used array methods:

- ’concat()’: Merges two or more arrays into a new array.


var arr1 = [1, 2];
var arr2 = [3, 4];
var mergedArr = [Link](arr2); // [1, 2, 3, 4]

- ’find()’: Returns the first element in the array that satisfies a specified
condition.
var arr = [5, 10, 15];
var found = [Link](num => num > 8); // 10

- ’includes()’: Checks if a specified element is in the array.


var arr = [2, 4, 6, 8];
var contains = [Link](4); // true

- ’indexOf()’: Finds the index of the first occurrence of a specified element in


the array.
var arr = [5, 10, 15];
var index = [Link](10); // 1

- ’isArray()’: Checks if a value is an array.


var arr = [2, 4, 6, 8];
var isArr = [Link](arr); // true

- ’join()’: Joins all the elements of an array into a single string.


var arr = [1, 2, 3];
var str = [Link]('-'); // "1-2-3"

- ’pop()’: Removes the last element from an array and returns that element.
var arr = [2, 4, 6];
var last = [Link](); // 6

- ’push()’: Adds one or more elements to the end of an array.


var arr = [2, 4, 6];
[Link](8); // [2, 4, 6, 8]

- ’reverse()’: Reverses the order of the elements in the array.


var arr = [1, 2, 3];
[Link](); // [3, 2, 1]

- ’slice()’: Returns a shallow copy of a portion of an array.


var arr = [2, 4, 6, 8];
var newArr = [Link](1, 3); // [4, 6]

- ’sort()’: Sorts the elements of the array in place.


var arr = [10, 5, 8];
[Link](); // [5, 8, 10]

- ’splice()’: Adds or removes elements from an array.


var arr = [2, 4, 6];
[Link](1, 0, 5); // [2, 5, 4, 6] (adds 5 at index 1)

Example: Adding/Append Object to Array

1. Using ‘push()’:
var arr = [2, 4, 6, 8];
var obj = {x: 5, y: "ten"};
[Link](obj);

2. Using ‘splice()’:

var arr = [2, 4, 6, 8];


var obj = {x: 5, y: "ten"};
var index = [Link];
[Link](index, 0, obj);

Checking if a Variable is an Array


- To check if a variable is an array, you can use the ‘[Link]()’ method:
var arr = [2, 4, 6, 8];
[Link]([Link](arr)); // true

Example: Checking the Type of an Array


- Even though arrays are objects in JavaScript, you can check the type using
‘typeof’. However, it will return "object" for arrays too:

var arr = [2, 4, 6, 8];


[Link](typeof(arr)); // "object"
Date in JavaScript
- The Date object in JavaScript is used to work with dates and times.
- It can represent any date and time with millisecond precision, ranging from 100
million days before or after January 1, 1970 (the Unix epoch).
- The month index in JavaScript starts from 0 (January) to 11 (December), which
is an important detail when working with Date objects.

Date Constructors
- JavaScript provides several ways to create Date objects:

1. No arguments:
- If no arguments are passed, it creates a Date object representing the current
date and time.
var currentDate = new Date();

2. Single argument (milliseconds):


- When a single numeric argument is passed, it represents the number of
milliseconds since January 1, 1970 (midnight UTC).

var dateFromMilliseconds = new Date(5000); // 5 seconds after 1970-01-


01T[Link]Z

3. Single argument (date string):


- If a string representing a date is passed, it creates a Date object using that
string.
var dateFromString = new Date("October 13, 2014 [Link]");

4. Multiple arguments:
- You can pass a year, month, day, hours, minutes, seconds, and milliseconds.
var d = new Date(2021, 3, 27, 15, 55, 30, 0);
// Output: Tue Apr 27 2021 [Link] GMT+0530 (India Standard Time)

Note: The month argument is 0-based, so 3 represents April, not March.


Example of Date Object Creation
- Current Date and Time:
var d = new Date();
[Link](d); // Current date and time

- Milliseconds since Unix Epoch:


[Link]([Link]()); // e.g., 1634907789708

- Date from a String:


var d = new Date("October 13, 2014 [Link]");
[Link](d); // Mon Oct 13 2014 [Link] GMT+0530 (India Standard Time)

- Date from Milliseconds:


const d = new Date(1634907789708);
[Link]([Link]()); // Output: 22/10/2021, [Link]

Date Methods
- Here are some commonly used methods for working with Date objects:

Get Methods :

- ’getDate()’: Returns the day of the month (1-31) for a specific date.
var d = new Date();
[Link]([Link]()); // Example: 27 (for 27th of the month)

- ’getDay()’: Returns the day of the week (0-6) for a specific date (0 = Sunday,
6 = Saturday).

[Link]([Link]()); // Example: 2 (for Tuesday)

- ’getFullYear()’: Returns the full year (e.g., 2021).

[Link]([Link]()); // Example: 2021


- ’getHours()’: Returns the hour of the day (0-23) based on local time.

[Link]([Link]()); // Example: 15

- ’getMilliseconds()’: Returns the milliseconds (0-999) for the specified date.

[Link]([Link]()); // Example: 500

- ’getMinutes()’: Returns the minutes (0-59) for the specified date.

[Link]([Link]()); // Example: 30

- ’getMonth()’: Returns the month (0-11) for the specified date (0 = January, 11
= December).

[Link]([Link]()); // Example: 3 (for April)

- ’getSeconds()’: Returns the seconds (0-59) for the specified date.

[Link]([Link]()); // Example: 45

Set Methods

- ’setDate()’: Sets the day of the month (1-31) for a specific date.

[Link](5);

- ’setDay()’: There is no direct ‘setDay()’ method in JavaScript Date; to set the


day of the week, you would use ‘setDate()’ in combination with ‘getDay()’.

- ’setFullYear()’: Sets the year for a specific date.

[Link](2022);
- ’setHours()’: Sets the hour (0-23) for a specific date.

[Link](10);

- ’setMilliseconds()’: Sets the milliseconds (0-999) for a specific date.

[Link](500);

- ’setMinutes()’: Sets the minutes (0-59) for a specific date.

[Link](30);

- ’setMonth()’: Sets the month (0-11) for a specific date.

[Link](5); // Sets to June

- ’setSeconds()’: Sets the seconds (0-59) for a specific date.

[Link](45);

Date Formatting Methods

- ’toDateString()’: Returns the date portion of a Date object as a string.

[Link]([Link]()); // Example: "Tue Apr 27 2021"

- ’toTimeString()’: Returns the time portion of a Date object as a string.

[Link]([Link]()); // Example: "[Link] GMT+0530 (India


Standard Time)"

- ’toUTCString()’: Returns the date and time in UTC format.


[Link]([Link]()); // Example: "Tue, 27 Apr 2021 [Link] GMT"

Expected Question :
1) List the various methods of Math object. Explain any one with example.

Math Object in JavaScript


- The Math object in JavaScript is a built-in object that provides various
mathematical functions and constants.
- It is not a constructor, meaning you can't create an instance of it. Instead, its
properties and methods are accessed directly from the Math object.

Mathematical Constants in JavaScript


vJavaScript provides several mathematical constants that can be accessed via
the Math object:

- ’Math.E’: Euler's number, approximately ‘2.718’.


- ’[Link]’: The mathematical constant PI, approximately ‘3.14159’.
- ’Math.SQRT2’: The square root of 2, approximately ‘1.414’.
- ’Math.SQRT1_2’: The square root of 1/2, approximately ‘0.707’.
- ’Math.LN2’: The natural logarithm of 2, approximately ‘0.693’.

- ’Math.LN10’: The natural logarithm of 10, approximately ‘2.303’.


- ’Math.LOG2E’: The base-2 logarithm of Euler's number, approximately ‘1.442’.
- ’Math.LOG10E’: The base-10 logarithm of Euler's number, approximately
‘0.434’.

Methods in the Math Object


- JavaScript's Math object provides several methods for performing
mathematical operations:

- ’[Link](x)’: Returns the absolute value of ‘x’.


[Link](-5); // Returns 5
- ’[Link](x)’: Returns the arccosine of ‘x’ in radians (inverse of cosine).

[Link](1); // Returns 0 (radians)

- ’[Link](x)’: Returns the arcsine of ‘x’ in radians (inverse of sine).

[Link](1); // Returns 1.5708 (radians)

- ’[Link](x)’: Returns the arctangent of ‘x’ in radians (inverse of tangent).

[Link](1); // Returns 0.7854 (radians)

- ’[Link](x)’: Returns the cube root of ‘x’.

[Link](8); // Returns 2

- ’[Link](x)’: Returns the smallest integer greater than or equal to ‘x’.

[Link](3.4); // Returns 4

- ’[Link](x)’: Returns the cosine of ‘x’ (angle in radians).

[Link]([Link]); // Returns -1

- ’[Link](x)’: Returns the hyperbolic cosine of ‘x’.

[Link](0); // Returns 1

- ’[Link](x)’: Returns ‘e’ raised to the power of ‘x’.

[Link](1); // Returns 2.718

- ’[Link](x)’: Returns the largest integer less than or equal to ‘x’.


[Link](3.7); // Returns 3

- ’[Link](x, y, ...)’: Returns the square root of the sum of squares of the
given numbers (Euclidean distance).

[Link](3, 4); // Returns 5 (Pythagorean theorem)

- ’[Link](x, y, ...)’: Returns the largest of the given numbers.

[Link](1, 3, 2); // Returns 3

- ’[Link](x, y, ...)’: Returns the smallest of the given numbers.

[Link](1, 3, 2); // Returns 1

- ’[Link](base, exponent)’: Returns the base raised to the power of exponent.

[Link](2, 3); // Returns 8

- ’[Link]()’: Returns a random number between 0 (inclusive) and 1


(exclusive).

[Link](); // Example: 0.574

- ’[Link](x)’: Returns the nearest integer to ‘x’.

[Link](3.5); // Returns 4

- ’[Link](x)’: Returns the sign of ‘x’: 1 if positive, -1 if negative, or 0 if zero.

[Link](-5); // Returns -1

- ’[Link](x)’: Returns the sine of ‘x’ (angle in radians).


[Link]([Link] / 2); // Returns 1

- ’[Link](x)’: Returns the hyperbolic sine of ‘x’.

[Link](0); // Returns 0

- ’[Link](x)’: Returns the square root of ‘x’.

[Link](16); // Returns 4

- ’[Link](x)’: Returns the tangent of ‘x’ (angle in radians).

[Link]([Link] / 4); // Returns 1

- ’[Link](x)’: Returns the hyperbolic tangent of ‘x’.

[Link](0); // Returns 0

- ’[Link](x)’: Returns the integer part of ‘x’ by removing any fractional


digits.

[Link](3.7); // Returns 3

Number in JavaScript
- The Number object in JavaScript is used to represent numeric values, which
can either be integers or floating-point numbers.
- JavaScript follows the IEEE standard for representing floating-point numbers.

Creating a Number Object


- You can create a Number object in JavaScript using the ‘Number()’
constructor:
var n = new Number(16);

- If the value cannot be converted to a number, the result will be ‘NaN’ (Not a
Number).

JavaScript Number Constants


- ’Number.MIN_VALUE’: Represents the smallest positive number that can be
represented in JavaScript (greater than 0).

- ’Number.MAX_VALUE’: Represents the largest positive number that can be


represented in JavaScript.

- ’Number.POSITIVE_INFINITY’: Represents positive infinity (overflow value).

- ’Number.NEGATIVE_INFINITY’: Represents negative infinity (overflow


value).

- ’[Link]’: Represents a "Not a Number" value, used to indicate a failed or


undefined numeric operation.

Methods in the Number Object


- ’[Link](value)’: Returns ‘true’ if the value is a finite number, otherwise
‘false’.

[Link](42); // Returns true

- ’[Link](value)’: Returns ‘true’ if the value is an integer, otherwise


‘false’.

[Link](42); // Returns true

- ’[Link](value)’: Converts a string to a floating-point number.


[Link]("3.14"); // Returns 3.14

- ’[Link](value)’: Converts a string to an integer.

[Link]("42"); // Returns 42

- ’toExponential(x)’: Returns a string representing the number in exponential


notation with ‘x’ digits after the decimal point.

(123456).toExponential(2); // Returns "1.23e+5"

- ’toFixed(x)’: Returns a string representing the number with exactly ‘x’ digits
after the decimal point.

(123.456).toFixed(2); // Returns "123.46"

- ’toPrecision(x)’: Returns a string representing the number with ‘x’ significant


digits.

(123.456).toPrecision(4); // Returns "123.5"

String in JavaScript
- A String in JavaScript is a sequence of characters enclosed in single or double
quotes.
- JavaScript does not distinguish between a single character and a string of
characters.

Creating a String
- There are two ways to create a string in JavaScript:

1. By string literal:

var str1 = "This is a string";


2. By string object (using ‘new’ keyword):

var str1 = new String("This is a string");

- Strings are associated with a String object, which provides several methods
for manipulating and examining strings.

String Object Methods

- ’charAt(index)’: Returns the character at the specified index.

"Hello".charAt(1); // Returns "e"

- ’concat(str1, str2, ...)’: Joins two or more strings and returns the concatenated
string.

"Hello".concat(" ", "World"); // Returns "Hello World"

- ’indexOf(searchValue)’: Returns the position of the first occurrence of the


specified character or substring.

"Hello World".indexOf("World"); // Returns 6

- ’search(regexp)’: Searches a string for a match against a regular expression


and returns the position of the match.

"Hello World".search("World"); // Returns 6

- ’match(regexp)’: Returns an array of matches of a regular expression in the


string.

"Hello World".match(/o/g); // Returns ["o", "o"]


- ’replace(searchValue, replaceValue)’: Replaces a specified substring with
another substring.

"Hello World".replace("World", "JavaScript"); // Returns "Hello JavaScript"

- ’substr(start, length)’: Returns a part of the string starting from ‘start’ index
and with ‘length’ characters.

"Hello World".substr(0, 5); // Returns "Hello"

- ’substring(start, end)’: Returns a part of the string between ‘start’ and ‘end’
index.

"Hello World".substring(0, 5); // Returns "Hello"

- ’slice(start, end)’: Extracts a part of the string and returns it as a new string.

"Hello World".slice(0, 5); // Returns "Hello"

- ’toLowerCase()’: Converts all characters in the string to lowercase.

"Hello".toLowerCase(); // Returns "hello"

- ’toUpperCase()’: Converts all characters in the string to uppercase.

"hello".toUpperCase(); // Returns "HELLO"

- ’toString()’: Returns the string representation of an object.

(123).toString(); // Returns "123"

- ’valueOf()’: Returns the primitive value of a string object.


new String("Hello").valueOf(); // Returns "Hello"

- ’split(separator)’: Splits the string into an array of substrings based on the


separator.

"Hello World".split(" "); // Returns ["Hello", "World"]

- ’trim()’: Removes whitespace from both ends of the string.

" Hello World ".trim(); // Returns "Hello World"

Object Types and Primitive Types in JavaScript


- In JavaScript, there are primitive types and object types. Each primitive type
has a corresponding built-in object that provides additional functionality.
- The key difference between these types is how they are handled by the
JavaScript engine, particularly in relation to how they are passed to functions
and manipulated.

Primitive Types
Primitive types in JavaScript include:
- String
- Number
- Boolean
- Undefined
- Null
- Symbol (new in ECMAScript 6)
- BigInt (for very large integers)

- These types are immutable (cannot be changed once created) and are passed
by value.
- This means when you assign a primitive value to a variable, a copy of the value
is stored, and any changes to the new variable do not affect the original variable.
Object Types
Objects in JavaScript are collections of properties and methods and include
types like:
- Object
- Array
- Function
- Date
- RegExp
- Error
- Map
- Set

- Objects are reference types, meaning they store a reference (or pointer) to
the location in memory where the actual data is stored.
- When an object is passed to a function, it's the reference that is passed,
allowing the function to modify the original object.

Built-In Object Versions of Primitives


Each primitive type has a corresponding built-in object:
- String → ‘String’ object
- Number → ‘Number’ object
- Boolean → ‘Boolean’ object

For example:
- You can create a String object using the ‘new String()’ constructor:

var strObj = new String("Hello");

- Similarly, you can create a Number object using ‘new Number()’:


var numObj = new Number(100);

- You can create a Boolean object using ‘new Boolean()’:


var boolObj = new Boolean(true);
- Although these objects exist, JavaScript automatically converts primitive
types into their corresponding object types when necessary.
- This process is called autoboxing. For instance, when you try to access a
method on a primitive, JavaScript will temporarily convert it into its object
counterpart.

When to Use Object Types Over Primitive Types


- There are two situations where you might prefer to use an object type instead
of the primitive type:

1. Adding instance properties:


- If you need to add custom properties to a primitive value, you must use the
object version.
- For example, primitive types like strings or numbers cannot have additional
properties, but objects can.

var strObj = new String("Hello");


[Link] = "This is custom"; // This works on the object version

2. Passing by reference to functions:


- Primitive values are passed by value to functions. This means if you modify the
parameter inside the function, it will not change the original value outside the
function.
- On the other hand, objects are passed by reference, so if you modify an object
inside a function, it will affect the original object.

function modifyString(str) {
str = "Modified";
}
var primitiveStr = "Hello";
modifyString(primitiveStr);
[Link](primitiveStr); // Output: "Hello", original string remains
unchanged
function modifyObject(obj) {
[Link] = "Changed";
}

var obj = { property: "Original" };


modifyObject(obj);
[Link]([Link]); // Output: "Changed", object is modified

When Not to Use Object Types


- Outside of the two cases mentioned above, there is no real performance or
memory usage advantage to using the object types over primitive types.
- Primitive types are simpler and more lightweight, so it's generally preferred
to use them unless you specifically need to add properties or pass them by
reference.
Some pyq’s program

Q. Write a JavaScript program to pass the function by reference, perform


addition of two objects inside the function and display the result in calling
function.

Q. Write a JavaScript program that will append an object to an array and will
check if an object is an array data types.

JavaScript program to pass the function by reference, perform addition of two


objects inside the function and display the result in calling function.

- In JavaScript, when we pass an object to a function, we are passing it by


reference.
- This means that any changes made to the object inside the function will
directly affect the original object.
- In this example, we'll create a JavaScript program that performs the addition
of two objects containing numeric values and then displays the result in the
calling function.

Steps to Implement the Program

1. Define two objects: These objects will contain numerical properties.


2. Pass the objects by reference: The objects will be passed to a function that
will add their properties.
3. Modify the objects inside the function: The function will perform the addition
on the object properties.
4. Display the result: After the addition, the modified objects will show the
updated result.
JavaScript Code

// Function to add properties of two objects


function addObjects(obj1, obj2) {
// Performing addition of the properties of two objects
[Link] = [Link] + [Link];
[Link] = [Link]; // Updating second object with the same result
}

// Main code
// Creating two objects with 'value' properties
let object1 = { value: 10 };
let object2 = { value: 20 };

// Displaying initial values


[Link]("Before Addition:");
[Link]("Object 1 value: " + [Link]);
[Link]("Object 2 value: " + [Link]);

// Calling the function and passing objects by reference


addObjects(object1, object2);

// Displaying the result after addition


[Link]("\nAfter Addition:");
[Link]("Object 1 value: " + [Link]); // Result is stored in object1
[Link]("Object 2 value: " + [Link]); // Result is also updated in
object2

Explanation
- Function ‘addObjects(obj1, obj2)’: This function takes two objects as
parameters (‘obj1’ and ‘obj2’) and adds their ‘value’ properties together. The
result is stored in ‘[Link]’ and also updated in ‘[Link]’.
- Objects (‘object1’, ‘object2’): Initially, the objects contain ‘value’ properties
with numbers (‘[Link] = 10’, ‘[Link] = 20’).

- Passing objects by reference: When we call ‘addObjects(object1, object2)’,


the actual objects are passed to the function, so any modification made to the
objects inside the function affects the original objects.

- Displaying the result: Before and after calling the function, we print the values
of the objects using ‘[Link]()’ to show the result of the addition.

Output
Before Addition:
Object 1 value: 10
Object 2 value: 20

After Addition:
Object 1 value: 30
Object 2 value: 30

JavaScript program that will append an object to an array and will check if an
object is an array data types.

In this JavaScript program, we will:


1. Append an object to an array.
2. Check if the object is an array using the ‘[Link]()’ method, which is a
built-in JavaScript function to determine if a value is an array.

Steps to Implement the Program:


1. Create an array: Define an array to which the object will be appended.
2. Create an object: Define an object that will be added to the array.
3. Use ‘push()’ method: This method will append the object to the array.
4. Use ‘[Link]()’: This method will check if the object is an array and
return a boolean value.

JavaScript Code:

// Step 1: Create an array


let myArray = ["apple", "banana", "cherry"];

// Step 2: Create an object


let myObject = { name: "John", age: 30 };

// Step 3: Append the object to the array using push() method


[Link](myObject);

// Step 4: Check if the appended object is an array using [Link]() method


[Link]("Is myObject an array?: " + [Link](myObject)); // This will
return false

// Step 5: Check if the updated array is an array


[Link]("Is myArray an array?: " + [Link](myArray)); // This will
return true

// Displaying the final array content after appending


[Link]("\nUpdated Array:");
[Link](myArray);

Explanation:

1. ‘myArray’: Initially, ‘myArray’ is an array with three elements (‘apple’, ‘banana’,


‘cherry’).
2. ‘myObject’: An object with properties ‘name’ and ‘age’ is created. The object
is not an array.
3. ‘push()’ Method: The ‘push()’ method adds ‘myObject’ to the end of the
‘myArray’ array. After this operation, ‘myObject’ is now a part of ‘myArray’.

4. ‘[Link]()’:
- ‘[Link](myObject)’ checks if ‘myObject’ is an array. It will return
‘false’ because ‘myObject’ is an object, not an array.
- ‘[Link](myArray)’ checks if ‘myArray’ is an array. It will return ‘true’
because ‘myArray’ is an array, even though it now contains an object.

5. Final Output:
- The program first checks if ‘myObject’ is an array and prints ‘false’.
- Then it checks if ‘myArray’ is an array and prints ‘true’.
- Finally, it prints the updated content of ‘myArray’, showing that ‘myObject’
is successfully appended.

Output:

Is myObject an array?: false


Is myArray an array?: true

Updated Array:
[ 'apple', 'banana', 'cherry', { name: 'John', age: 30 } ]
Unit -4 Regular Expressions

Expected Question :

-> What is Regular Expression in JavaScript and explain the need of regular
expressions.
-> Explain Look ahead and Look behind concepts in JavaScript.
-> Write a program to study string related built-in methods in JavaScript.
-> Explain string methods for Regular Expression in JavaScript.
-> Explain Character Classes in JavaScript.
-> What are the limitations of Regular Expression?
-> What are common character classes in Regular Expressions?
-> Write a short note on Advanced Regular Expressions.
-> List String Methods for Regular Expressions and explain any one of them.
-> List the 6 Repetition Quantifiers with their meaning. Explain any 2 with
example.
-> Explain Static Properties of the RegExp Class Object.
-> Describe Limitations of Regular Expressions.
Regular Expressions in JavaScript

Expected Question :
1) What is Regular Expression in JavaScript and explain the need of
regular expressions.

- Regular expressions (RegExp) are patterns used for matching and manipulating
strings.
- They are commonly used for validating input, parsing text, and performing
search-and-replace operations.
- JavaScript introduced regular expressions with the ‘RegExp’ object.

Features of Regular Expressions:


1. Pattern Matching: Matches specific sequences of characters in a string.

2. Validation: Validates user input like phone numbers, email addresses, etc.

3. Search and Replace: Simplifies tasks like finding specific patterns and
replacing them with new content.

4. Compact Code: Allows complex operations in fewer lines of code compared to


traditional string manipulation.

Example: Validating a Phone Number

Phone number format: ‘NNN-NNN-NNNN’ where N is a digit.

Without Regular Expressions:

function isDigit(character) {
return character >= '0' && character <= '9';
}
function isPhoneNumber(phone) {
if ([Link] !== 12) return false;

for (var i = 0; i < 12; i++) {


if (i === 3 || i === 7) {
if ([Link](i) !== '-') return false;
} else {
if (!isDigit([Link](i))) return false;
}
}
return true;
}

With Regular Expressions:

function isPhoneNumber(phone) {
var phoneRegex = /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/;
return [Link](phone);
}

Common Regular Expression Patterns:

- Anchors:
- ‘^’ matches the start of a string.
- ‘$’ matches the end of a string.

- Quantifiers:
- ‘{n}’: Matches exactly n occurrences.
- ‘{n,}’: Matches at least n occurrences.
- ‘{n,m}’: Matches between n and m occurrences.
- ‘*’: Matches 0 or more occurrences.
- ‘+’: Matches 1 or more occurrences.
- ‘?’: Matches 0 or 1 occurrence.

- Character Classes:
- ‘[0-9]’: Matches a single digit.
- ‘[a-zA-Z]’: Matches a single letter (lowercase or uppercase).
- ‘.’: Matches any single character except newline.
- ‘\d’: Matches any digit (equivalent to ‘[0-9]’).
- ‘\D’: Matches any non-digit.
- ‘\w’: Matches any word character (alphanumeric + ‘_’).
- ‘\W’: Matches any non-word character.

Validating Other Inputs:


- Email:
var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
[Link]([Link]("example@[Link]")); // true

- URL:
var urlRegex = /^(https?:\/\/)?(www\.)?[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\/?$/;
[Link]([Link]("[Link] // true

Key Methods:
1. ‘test()’: Checks if a string matches the pattern.
javascript
/abc/.test("abcdef"); // true

2. ‘match()’: Extracts matching parts of a string.


javascript
"abc123".match(/\d+/); // ["123"]

3. ‘replace()’: Replaces matched parts of a string.


javascript
"123-456".replace(/-/g, ":"); // "123:456"
4. ‘split()’: Splits a string based on a pattern.
javascript
"a,b,c".split(/,/); // ["a", "b", "c"]

Need for Regular Expressions in JavaScript


- Regular expressions are powerful tools that simplify string matching,
validation, and manipulation.
- Their utility lies in reducing code complexity and enabling concise handling of
complex patterns.

Why Use Regular Expressions:


1. Simplify Code: Reduces the complexity of validating structured data like phone
numbers, email addresses, and URLs.
2. Pattern Matching: Matches specific patterns in strings, such as data formats
(e.g., date, currency).
3. Text Manipulation: Extracts or replaces specific parts of text efficiently.
4. Validation: Ensures the correctness of user input in predictable formats.
5. Flexibility: Operates on any string data with a structured format.
6. Reusable Patterns: Can be used across multiple fields or contexts in forms.

Creating Patterns:
- Regular expressions can be created in two ways:
1. Literal Syntax:
javascript
var pattern = /http/;

2. Using ‘RegExp’ Object:


javascript
var pattern = new RegExp("http");

- Both patterns match any string containing "http".


Example:
var str = "[Link]
[Link](str); // true

Flags for Regular Expressions:


- Flags modify how patterns are interpreted.
- 'i': Case-insensitive matching
- 'm': Multiline matching
- 'u': Unicode search
- 'g': Global search for all matches

Example:

var pattern = /http/i;


var str = "HTTP://[Link]";
[Link](str); // true

You can combine multiple flags:

var pattern = /http/gi;

Positional Indicators:
These special characters ensure that patterns match specific parts of a
string:
- ‘^’ Matches the beginning of a string.
- ‘$’ Matches the end of a string.

Examples:
- Beginning Match:
var pattern = /^http/;
var str = "http is a protocol";
[Link](str); // true

- End Match:
var pattern = /http$/;
var str = "The protocol is http";
[Link](str); // true

- Exact Match:
var pattern = /^http$/;
var str1 = "http";
var str2 = "http is used";
[Link](str1); // true
[Link](str2); // false

- Regular expressions offer immense versatility, enabling efficient validation,


matching, and manipulation of string data with minimal code.

Escape Codes in Regular Expressions=


- Escape codes are used in regular expressions to represent characters that
have special meanings.
- They are indicated using a backslash (‘\’) to ensure the correct interpretation
of these characters.

Why Escape Codes are Needed:


1. Certain characters like ‘/’, ‘.’, ‘*’, and ‘+’ have special meanings in regular
expressions.
2. To include such characters literally in a pattern, their special meaning must
be "escaped."
3. Helps match patterns containing reserved or special characters.

Example:
To match the URL pattern ‘[Link] you must escape ‘/’ and ‘.’:
var pattern = /http:\/\/www\.w3c\.org\//;

Here:
- ‘\/’ escapes ‘/’.
- ‘\.’ escapes ‘.’.

Common Escape Codes:

- ‘\f’ - Form feed


- ‘\n’ - Newline
- ‘\r’ - Carriage return
- ‘\t’ - Tab
- ‘\v’ - Vertical tab
- ‘\\’ - Backslash
- ‘\b’ - Word boundary
- ‘\d’ - Any digit (0–9)
- ‘\w’ - Any word character
- ‘\s’ - Whitespace character

Example Usage:

1. Matching a Literal Dot (‘.’):


javascript
var pattern = /a\.b/;
var str1 = "a.b"; // Matches
var str2 = "acb"; // Does not match

2. Matching a URL with Slashes (‘/’):


javascript
var urlPattern = /http:\/\/example\.com\//;
var url = "[Link]
[Link](url); // true
3. Matching Digits Only:
javascript
var digitPattern = /\d+/;
var numStr = "12345";
[Link](numStr); // true

Repetition Quantifiers in Regular Expressions

Expected Question :
1) List the 6 Repetition Quantifiers with their meaning. Explain any 2 with
example.

- Repetition quantifiers specify how many times the preceding element must
appear in a string for a match.
- Here is an explanation with examples for better understanding:

Quantifiers and Their Meanings


- Here are the character meanings in simple format:
- ‘*’ - Matches zero or more occurrences of the preceding item.
- ‘+’ - Matches one or more occurrences of the preceding item.
- ‘?’ - Matches zero or one occurrence of the preceding item.
- ‘{m}’ - Matches exactly m occurrences of the preceding item.
- ‘{m,n}’ - Matches between m and n occurrences of the preceding item.
- ‘{m,}’ - Matches at least m occurrences of the preceding item.

Examples of Quantifiers

1. Asterisk (‘*’) – Zero or More Occurrences:


This quantifier allows the preceding character to appear any number of times,
including zero.
var pattern = /ab*c/;
var string = "abc ac abbbc";
[Link]([Link](pattern)); // Output: 'abc'

- Matches "a", followed by zero or more "b", followed by "c".


- Examples of strings that match: "ac", "abc", "abbbc".

2. Plus (‘+’) – One or More Occurrences:


This quantifier ensures the preceding character appears at least once.

var pattern = /ab+c/;


var string = "abc ac abbbc";
[Link]([Link](pattern)); // Output: 'abc'

- Matches "a", followed by one or more "b", followed by "c".


- Examples of strings that match: "abc", "abbbc".
- Does not match "ac" since there is no "b".

3. Question Mark (‘?’) – Zero or One Occurrence:


The question mark makes the preceding character optional.

var pattern = /ab?c/;


var string = "ac abc abbc";
[Link]([Link](pattern)); // Output: 'ac'

- Matches "a", followed by zero or one "b", followed by "c".


- Examples of strings that match: "ac", "abc".
- Does not match "abbc" as there are too many "b" characters.

4. Curly Braces (‘{m}’) – Exact Number of Occurrences:


This quantifier specifies an exact number of times the preceding character
should appear.
var pattern = /ab{3}c/;
var string = "abbbc abbc abc";
[Link]([Link](pattern)); // Output: 'abbbc'

- Matches "a", followed by exactly three "b", followed by "c".


- Only "abbbc" matches this pattern.

5. Curly Braces with Range (‘{m,n}’) – Between ‘m’ and ‘n’ Occurrences:
This quantifier specifies a range for how many times the preceding character
can appear.

var pattern = /ab{2,4}c/;


var string = "abc abbc abbbc abbbbc";
[Link]([Link](pattern)); // Output: 'abbc'

- Matches "a", followed by between 2 and 4 "b", followed by "c".


- Examples of strings that match: "abbc", "abbbc", "abbbbc".
- Does not match "abc" since it has less than 2 "b".

6. Curly Braces with Lower Limit Only (‘{m,}’) – At Least ‘m’ Occurrences:
This quantifier ensures the preceding character appears at least ‘m’ times with
no upper limit.

var pattern = /ab{3,}c/;


var string = "abc abbc abbbc abbbbc";
[Link]([Link](pattern)); // Output: 'abbbc'

- Matches "a", followed by at least three "b", followed by "c".


- Examples of strings that match: "abbbc", "abbbbc".

Advanced Usage of Quantifiers


1. Combining Quantifiers for Patterns:
You can use quantifiers to match specific patterns like phone numbers.
var pattern = /\d{3}-\d{3}-\d{4}/;
var string = "123-456-7890";
[Link]([Link](pattern)); // Output: '123-456-7890'

- Matches three digits, followed by a hyphen, three more digits, another


hyphen, and four digits.

2. Character Classes with Quantifiers:


Use quantifiers with character classes to match groups of characters.

var pattern = /[a-z]{5}/;


var string = "hello world";
[Link]([Link](pattern)); // Output: 'hello'

- Matches exactly five lowercase letters.


- "hello" is the first match in the string.

3. Anchors with Quantifiers:


Use anchors to specify the beginning and end of a string.

var pattern = /^\d{2}-\d{2}-\d{4}$/;


var string = "12-34-5678";
[Link]([Link](pattern)); // Output: '12-34-5678'

- Matches a string that starts with two digits, a hyphen, two more digits,
another hyphen, and four digits, ending there.

4. Lazy Quantifiers:
Lazy quantifiers make the match as short as possible.

var pattern = /a*?b/;


var string = "aaab";
[Link]([Link](pattern)); // Output: 'ab'
- Matches "a" repeated zero or more times (minimally), followed by "b".

5. Using Non-Capturing Groups with Quantifiers:


Non-capturing groups allow matching without capturing the group in the result.

var pattern = /\d{2}(?:-\d{2}){2}/;


var string = "12-34-56";
[Link]([Link](pattern)); // Output: '12-34-56'

- Matches "12" followed by two groups of "-34" and "-56", but does not capture
them.

By understanding these quantifiers and combining them with other regular


expression features, you can create powerful patterns to match and manipulate
text in JavaScript.

Grouping in Regular Expressions


- Grouping in regular expressions is done using parentheses ‘()’.
- When you group characters or patterns using [Link] are treated as
a single unit, allowing you to apply quantifiers or other operators to the entire
group.
- This helps to manage complex patterns efficiently.

How Grouping Works


1. Basic Grouping:
- Using parentheses allows you to group expressions together.
- For example, if you want to match a sequence of characters multiple times, you
can wrap them in parentheses.

Example 1:

var pattern = /(ab)+/;


var str = "abcbcbcbcbcbcdef";
var result = [Link](pattern);
[Link](result); // Output: 'ab'

- Explanation: The pattern ‘(ab)+’ matches "ab" one or more times in the string.
Here, "ab" repeats multiple times, so the result is "ab".
- Reading the pattern: "a" followed by "b", repeated one or more times.

2. Using Quantifiers with Grouping:


You can combine grouping with quantifiers to match repeated patterns.

Example 2:

var pattern = /(very){3,5}hot/;


var str = "veryveryveryhot";
var result = [Link](pattern);
[Link](result); // Output: 'veryveryveryhot'

- Explanation: The pattern ‘(very){3,5}’ matches the word "very" repeated 3 to


5 times, followed by the word "hot".
- Reading the pattern: The word "very" repeated at least 3 times but no more
than 5 times, followed by "hot".
- This would also match strings like "veryveryhot", "veryveryveryhot", etc.

Advanced Grouping Techniques

1. Capture Groups:
- Parentheses also create *capture groups*. These are parts of the matched
pattern that can be referenced later in the regular expression or extracted
from the match results.

Example 3:
var pattern = /(\d{3})-(\d{3})-(\d{4})/;
var str = "123-456-7890";
var result = [Link](pattern);
[Link](result); // Output: ['123-456-7890', '123', '456', '7890']

- Explanation: The pattern creates three capture groups, one for each section
of the phone number. The result is an array where the first element is the entire
match, followed by each captured group (the three parts of the phone number).

2. Non-Capturing Groups:
- If you need to group a part of the regular expression but don’t want to
capture it (i.e., it is not needed in the result array), you can use a *non-capturing
group* with ‘(?:...)’.

Example 4:

var pattern = /(?:abc)+/;


var str = "abcabcabcabc";
var result = [Link](pattern);
[Link](result); // Output: 'abcabcabcabc'

- Explanation: The non-capturing group ‘(?:abc)’ matches "abc" one or more


times, but it does not create a separate capture group. The entire match
"abcabcabcabc" is returned, but "abc" is not captured individually.

3. Alternation within Groups:


- Inside a group, you can use the alternation operator ‘|’ to match different
options.

Example 5:
var pattern = /(cat|dog)+/;
var str = "catdogcat";
var result = [Link](pattern);
[Link](result); // Output: 'catdogcat'
- Explanation: The alternation operator ‘|’ inside the group matches either
"cat" or "dog" one or more times. In this example, the pattern matches the string
"catdogcat".

4. Nested Groups:
- Groups can be nested inside other groups, which helps create more complex
matching patterns.

Example 6:
var pattern = /((ab){2})+/;
var str = "abababab";
var result = [Link](pattern);
[Link](result); // Output: 'abababab'

- Explanation: The pattern ‘((ab){2})+’ first groups "ab", then repeats it exactly
two times, and this sequence can repeat one or more times.
- This allows "abababab" to match the pattern.

5. Group with a Quantifier:


When applying a quantifier to a group, the quantifier affects the entire group,
not just a single element.

Example 7:
var pattern = /(ab){3,5}/;
var str = "ababababab";
var result = [Link](pattern);
[Link](result); // Output: 'ababababab'

- Explanation: The pattern matches the group "ab" repeated between 3 and 5
times. In this case, it matches "ababababab".
Character Classes in Regular Expressions

Expected question :
1) Explain Character Classes in JavaScript.
2) What are common character classes in Regular Expressions?

- Character classes allow you to match any character from a specified set or
group.
- They are defined within square brackets ‘[]’. Anything inside the brackets is
treated as a single unit that can match any one character from the set.

Basic Character Classes

1. Matching Specific Characters:


A character class can match any of the individual characters it contains.

Example 1:
var pattern = /[pbm]111/;
var str = "p111";
var result = [Link](pattern);
[Link](result); // Output: ['p111']

- Explanation: The class ‘[pbm]’ matches any one of the characters ‘p’, ‘b’, or
‘m’ followed by ‘111’. This will match ‘p111’, ‘b111’, and ‘m111’, but not ‘c111’.

2. Matching Digits:
- You can define a class to match digits using ‘0-9’ or specify them individually.

Example 2:
var pattern = /[1234567890]+/;
var str = "123456";
var result = [Link](pattern);
[Link](result); // Output: ['123456']
- Explanation: The pattern ‘[1234567890]’ matches any digit from 0 to 9. The
‘+’ quantifier means the pattern will match one or more digits.

Using Dash (‘-’) for Ranges


- Instead of listing each character individually, you can use a dash (‘-’) to specify
a range of characters.

Example 3:
var pattern = /[0-9]+/;
var str = "987654";
var result = [Link](pattern);
[Link](result); // Output: ['987654']

- Explanation: The pattern ‘[0-9]’ matches any digit, the same as ‘[1234567890]’,
but more compactly. This matches strings containing one or more digits.

Examples with Range:

1. Lowercase Letters:
var pattern = /[a-z]+/;
var str = "hello";
var result = [Link](pattern);
[Link](result); // Output: ['hello']

2. Uppercase and Lowercase Letters:


var pattern = /[a-zA-Z]+/;
var str = "HelloWorld";
var result = [Link](pattern);
[Link](result); // Output: ['HelloWorld']

3. Alphanumeric Characters:
var pattern = /[a-zA-Z0-9]+/;
var str = "abc123";
var result = [Link](pattern);
[Link](result); // Output: ['abc123']

4. Matching a Specific Username Format:


var pattern = /^[a-z][a-z0-9_]*$/;
var str = "user_123";
var result = [Link](pattern);
[Link](result); // Output: ['user_123']

- Explanation: This pattern matches usernames that start with a lowercase


letter followed by any combination of lowercase letters, digits, or underscores.
It would match ‘m’, ‘m10_120’, or ‘abra_cadabra’, but not ‘_user’ or ‘10abc’.

Negative Character Classes


- Negative character classes match any character *except* those specified
inside the brackets.
- You can create a negative character class by placing a caret (‘^’) at the
beginning of the class.

Example 4:
var pattern = /[^a-zA-Z]+/;
var str = "12345!";
var result = [Link](pattern);
[Link](result); // Output: ['12345!']

- Explanation: The pattern ‘[^a-zA-Z]’ matches any character that is not a letter
(either lowercase or uppercase). In this example, it matches the digits and
special characters in the string.

Using Negative Classes for Parsing


- Negative character classes are often useful for parsing or matching strings
that contain specific delimiters, such as a comma.

Example 5:
var pattern = /[^,]+, [^,]+, [^,]+, [^,]+, [^,]+/;
var str = "peter, paul, mary, larry, moe";
var result = [Link](str);
[Link](result); // Output: true

- Explanation: This pattern matches five comma-separated values (i.e., five


strings separated by commas). The negative class ‘[^,]’ matches any character
that isn't a comma, and ‘[^,]+’ matches one or more characters that aren't
commas, followed by a comma.

More Compact Version:

var pattern = /[^,]+(, [^,]+){4}/;


var str = "peter, paul, mary, larry, moe";
var result = [Link](str);
[Link](result); // Output: true

- Explanation: This is a more concise version of the previous pattern, using ‘(,
[^,]+){4}’ to match the repeated comma-separated values.

Practical Example:
To test for five comma-separated values:

[Link]("peter, paul, mary, larry"); // false


[Link]("peter, paul, mary, larry, moe"); // true
Common Character Classes in Regular Expressions

Expected Question :
What are common character classes in Regular Expressions?

- Character classes provide shorthand escape codes to make patterns more


concise and easier to understand.

- Here are the most commonly used shorthand character classes:

1. ‘.’ (Period)
- The period matches any single character except for newline characters. This
is useful when you want to match any character in a string.

Example:
var pattern = /abc..d/;
var str = "abcX7d";
var result = [Link](pattern);
[Link](result); // Output: ['abcX7d']

- Explanation: The pattern ‘abc..d’ matches any string that starts with ‘abc’,
followed by any two characters, and ends with ‘d’.

2. ‘\w’ (Word Character)


- Matches any word character, which is equivalent to ‘[a-zA-Z0-9_]’. This
includes lowercase and uppercase letters, digits, and the underscore ‘_’.

Example:
var pattern = /\w+/;
var str = "Hello123";
var result = [Link](pattern);
[Link](result); // Output: ['Hello123']
- Explanation: The pattern ‘\w+’ matches one or more word characters.

3. ‘\W’ (Non-Word Character)


- Matches any character that is not a word character, i.e., anything that is not
‘[a-zA-Z0-9_]’.

Example:
var pattern = /\W+/;
var str = "Hello 123!";
var result = [Link](pattern);
[Link](result); // Output: [' ']

- Explanation: The pattern ‘\W+’ matches one or more non-word characters, such
as spaces, punctuation, etc.

4. ‘\s’ (Whitespace Character)


- Matches any whitespace character, which includes spaces, tabs, line breaks,
etc. It is equivalent to ‘[ \t\n\r\f\v]’.

Example:
var pattern = /\s+/;
var str = "Hello world!";
var result = [Link](pattern);
[Link](result); // Output: [' ']

- Explanation: The pattern ‘\s+’ matches one or more whitespace characters.

5. ‘\S’ (Non-Whitespace Character)


- Matches any character that is not a whitespace character, i.e., it is equivalent
to ‘[^ \t\n\r\f\v]’.

Example:
var pattern = /\S+/;
var str = "Hello world!";
var result = [Link](pattern);
[Link](result); // Output: ['Hello']

- Explanation: The pattern ‘\S+’ matches one or more non-whitespace characters.

6. ‘\d’ (Digit)
- Matches any digit, equivalent to ‘[0-9]’.

Example:
var pattern = /\d+/;
var str = "12345";
var result = [Link](pattern);
[Link](result); // Output: ['12345']

- Explanation: The pattern ‘\d+’ matches one or more digits.

7. ‘\D’ (Non-Digit)
- Matches any character that is not a digit, equivalent to ‘[^0-9]’.

Example:
var pattern = /\D+/;
var str = "abc123";
var result = [Link](pattern);
[Link](result); // Output: ['abc']

- Explanation: The pattern ‘\D+’ matches one or more non-digit characters.

8. ‘\b’ (Word Boundary)


- Matches a word boundary, which is the position between a word character (‘\w’)
and a non-word character (‘\W’).

Example:
var pattern = /\bword\b/;
var str = "word boundary test";
var result = [Link](pattern);
[Link](result); // Output: ['word']

- Explanation: The pattern ‘\bword\b’ matches the word ‘word’ only when it is a
separate word (i.e., not part of another word like ‘sword’).

9. ‘\B’ (Non-Word Boundary)


- Matches any position that is not a word boundary.

Example:
var pattern = /\Bword\B/;
var str = "sword";
var result = [Link](pattern);
[Link](result); // Output: ['word']

- Explanation: The pattern ‘\Bword\B’ matches ‘word’ when it is not at the


boundary of a word (e.g., part of ‘sword’).

10. ‘[\b]’ (Backspace)


- The ‘\b’ is a special escape sequence in JavaScript regular expressions.
- But ‘[\b]’ matches the backspace character, which is not commonly used in
modern regular expressions.

Using Character Classes for Pattern Matching


- Character classes are often used to create more readable and efficient regular
expressions.
- Here’s an example of using these classes to validate a North American phone
number:

Example: North American Phone Number


var pattern = /^\d{3}-\d{3}-\d{4}$/;
var phone = "123-456-7890";
var result = [Link](phone);
[Link](result); // Output: true

- Explanation: The pattern ‘^\d{3}-\d{3}-\d{4}$’ ensures that the phone number


matches the format of three digits, followed by a hyphen, another three digits,
another hyphen, and four digits.

Alternatives (‘|’ or Logical OR)

- You can use the pipe (‘|’) operator to define alternatives within a regular
expression.
- It works like a logical OR, where the pattern will match any one of the options.

Example: Matching Multiple Protocols


var pattern = /^(http|ftp|https)/;
var str = "ftp is file transfer protocol";
var result = [Link](pattern);
[Link](result); // Output: ['ftp']

- Explanation: The pattern ‘^(http|ftp|https)’ matches a string that starts with


either ‘http’, ‘ftp’, or ‘https’.

Alternation with Parentheses:


- When alternation is used within parentheses, the logical OR applies to the
entire group inside the parentheses.

Example:
var pattern = /(James|Jim|Charlie) Brown/;
var str = "James Brown";
var result = [Link](pattern);
[Link](result); // Output: ['James Brown']
- Explanation: The pattern ‘(James|Jim|Charlie) Brown’ matches "James Brown",
"Jim Brown", or "Charlie Brown".

If you remove the parentheses, it will no longer work as intended:

Incorrect Example:
var pattern = /^http|ftp|https/;
var str = "ftp is file transfer protocol";
var result = [Link](pattern);
[Link](result); // Output: ['ftp']

- Explanation: Without the parentheses, the pattern matches any string


containing ‘http’, ‘ftp’, or ‘https’, not necessarily at the beginning of the string.

RegExp Object in JavaScript

- In JavaScript, the RegExp (Regular Expression) class is used to represent


regular expressions.
- The RegExp object provides various methods that allow you to perform
powerful pattern-matching and search-and-replace functions on text.

Defining Regular Expressions


Regular expressions can be defined in two ways:

1. Literal Syntax:
var pattern = /abc/;

This is the simplest and most common way to define a regular expression.

2. Using the RegExp Constructor:


var pattern = new RegExp("abc");
- The constructor allows you to create a regular expression from a string, and
it can also accept flags (like ‘i’ for case-insensitivity).

Methods of the RegExp Object

1. ‘test()’
- The ‘test()’ method is the simplest RegExp method and returns a Boolean value
indicating whether a given string matches the regular expression.

Example:
var pattern = /http/;
var str = "http is a protocol";
[Link]([Link](str)); // Output: true

- Explanation: The pattern ‘/http/’ is tested against the string ‘"http is a


protocol"‘. Since the string contains ‘"http"‘, the method returns ‘true’.

2. ‘compile()’
- The ‘compile()’ method is used to replace an existing regular expression with a
new one. It takes the same arguments as the ‘RegExp’ constructor.

Example:
var pattern = new RegExp("http", "i");
[Link]("http+", "i");
[Link]([Link]("http is a protocol")); // Output: true

- Explanation: Initially, the regular expression ‘/http/i’ is created to find "http"


in any case. After calling ‘compile()’, it changes to ‘"http+"‘, which matches "http"
one or more times.

- Efficiency: Using ‘compile()’ helps to avoid recompiling the same regular


expression multiple times, improving performance, especially when dealing with
complex patterns.
3. ‘exec()’
- The ‘exec()’ method is used when you need additional information about the
match, like its position in the string.
- It can also be used repeatedly to find matches across a string.

- Return Value: The ‘exec()’ method returns an array with various properties:
- ‘input’: The original input string.
- ‘index’: The position where the match starts.
- ‘lastIndex’: The position where the next match will start.

Example:
var pattern = /cat/;
var str = "He is a big cat, a fat black cat named Rufus.";
var result = [Link](str);
[Link](result);

- Output:
[
"cat", // Full match
index: 13, // Starting position of the match
input: "He is a big cat, a fat black cat named Rufus.", // The original string
lastIndex: 16 // Next search will begin after this index
]

Using ‘exec()’ with Parentheses (Subexpressions)


- When using parentheses to define subexpressions in your regular expression,
the ‘exec()’ method returns an array with the full match at index 0 and each
subexpression match at subsequent indices.

Example:
var pattern = /(cat) (and) (dog)/;
var str = "My cat and dog are black.";
var result = [Link](str);
[Link](result);

- Output:
[
"cat and dog", // Full match
"cat", // First subexpression (cat)
"and", // Second subexpression (and)
"dog", // Third subexpression (dog)
length: 4, // Total number of elements in the result
index: 3, // Position where the match starts
input: "My cat and dog are black." // The original string
]

- Explanation: In this case, the pattern ‘/(cat) (and) (dog)/’ matches the string
"cat and dog" and captures "cat", "and", and "dog" as separate subexpressions.

Sub-Expressions in JavaScript RegExp


- In JavaScript, sub-expressions allow you to capture specific parts of a string
that match portions of a regular expression pattern.
- This is done using parentheses ‘()’ to group sections of the regular expression.
When a pattern with sub-expressions matches a string, the captured substrings
can be accessed individually.

Example of Sub-Expressions

- Consider a scenario where you want to extract first names and phone numbers
from a string that follows the format: ‘Firstname Lastname NNN-NNNN’ (where
‘N’ represents digits of a phone number).
You can use the following regular expression:
var pattern = /(\w+)\w+([\d-]{8})/;

Here, the pattern:


- ‘(\w+)’ captures one or more word characters (for the first name),
- ‘\w+’ matches the last name (which we do not capture),
- ‘([\d-]{8})’ captures a string of 8 characters that can be digits or dashes
(representing the phone number).

Accessing Sub-Expression Matches

- When this regular expression matches a string, the portions inside the
parentheses are saved as sub-expressions.
- You can access these captured substrings using special properties ‘$1’ to ‘$9’
from the ‘RegExp’ object.

Example:
var pattern = /(\w+)\w+([\d-]{8})/;
var str = "Alan Turing 555-1212";
if ([Link](str)) {
alert("RegExp.$1 = " + RegExp.$1); // Output: "Alan"
alert("RegExp.$2 = " + RegExp.$2); // Output: "555-1212"
}

- Explanation:
- The first sub-expression ‘(\w+)’ captures ‘"Alan"‘, and this can be accessed
via ‘RegExp.$1’.
- The second sub-expression ‘([\d-]{8})’ captures ‘"555-1212"‘, and this can be
accessed via ‘RegExp.$2’.

RegExp Properties
- JavaScript's ‘RegExp’ object has several properties that can be useful for
debugging and understanding regular expressions.
- These properties provide details about the state of the regular expression
instance.

Instance Properties

1. global
- Type: Boolean
- Description: Indicates if the global (‘g’) flag is set.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // true

2. ignoreCase (i)
- Type: Boolean
- Description: Indicates if the case-insensitive (‘i’) flag is set.
- Example:
javascript
var pattern = /(cat)(dog)/i;
[Link]([Link]); // true

3. lastIndex
- Type: Integer
- Description: Specifies the position in the string where the next match will
begin. Can be modified directly.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // 17
4. multiline (m)
- Type: Boolean
- Description: Indicates if the multiline (‘m’) flag is set.
- Example:
javascript
var pattern = /(cat)(dog)/m;
[Link]([Link]); // true

5. source
- Type: String
- Description: The string form of the regular expression (without flags).
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]([Link]); // "(cat)(dog)"

Static Properties (Class Properties)

Expected Question :
b) Explain Static Properties of the RegExp Class Object.

- These properties are accessed from the ‘RegExp’ class and are used to handle
results from the most recent match.

1. $1, $2, ..., $9


- Description: Holds the text matched by the first to the ninth parenthesized
subexpression.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link](RegExp.$1); // "cat"
[Link](RegExp.$2); // "dog"

2. index
- Type: Integer
- Description: The position of the first character of the last match.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // 10

3. input
- Type: String
- Description: The string that was tested against the regular expression.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // "this is a cat dog and cat dog"

4. lastIndex
- Type: Integer
- Description: Specifies the position in the string where the next match will
begin, for global matches.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // 17

5. lastMatch
- Type: String
- Description: Contains the most recently matched text.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // "cat dog"

6. lastParen
- Type: String
- Description: Contains the text of the last parenthesized subexpression of
the most recent match.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // "dog"

7. leftContext
- Type: String
- Description: Contains the text to the left of the most recent match.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // "this is a "

8. rightContext
- Type: String
- Description: Contains the text to the right of the most recent match.
- Example:
javascript
var pattern = /(cat)(dog)/g;
[Link]("this is a cat dog and cat dog");
[Link]([Link]); // " and cat dog"
Dynamic Scoping of Static Properties
- Static properties of ‘RegExp’ are dynamically scoped, meaning they reflect the
context of the most recent regular expression operation, not the scope in which
the regular expression was defined.
- This is especially important when working with regular expressions across
different contexts, such as in frames or multiple function calls.

- For example, in a situation where a regular expression is used in an iframe,


changes to static properties like ‘$1’ or ‘lastIndex’ are reflected in the context
where the regular expression is applied, not in the iframe or its origin context.

String Methods for Regular Expressions

Expected Question :
a) Explain string methods for Regular Expression in JavaScript.

- The ‘String’ object offers several methods that work with regular expressions,
providing powerful tools for string manipulation.
- These methods not only match patterns but can also modify strings based on
those patterns.

1. ‘search()’
- Purpose: Finds the index of the first match of a regular expression within a
string.
- Returns: The index of the first matching substring or ‘-1’ if no match is found.
- Example:
var pattern = /pow.*/i;
var str = "JavaScript regular expressions are powerful!";
var result = [Link](pattern);
[Link](result); // Prints: 35 (index of "powerful!")

2. ‘split()’
- Purpose: Splits a string into an array of substrings using a regular expression
as the delimiter.
- Example:
var str = "I am, string, break it.";
var result = [Link](",");
[Link](result); // Prints: ["I am", " string", " break it."]

- With Regular Expressions: You can split based on patterns like spaces or
slashes.
javascript
var limiter = /[\/]+/; // one or more slashes
var str = "10/3/14/7/9";
var result = [Link](limiter);
[Link](result); // Prints: ["10", "3", "14", "7", "9"]

3. ‘replace()’
- Purpose: Replaces the first occurrence of a pattern in a string with a
replacement string.
- Example:
var pattern = /\./;
var newStr = "1";
var str = "Hello. Regexps are fun.";
var result = [Link](pattern, newStr);
[Link](result); // Prints: "Hello1 Regexps are fun."

- With Global Flag: Use the ‘g’ flag to replace all occurrences.
javascript
var pattern = /\./g;
var newStr = "1";
var str = "Hello. Regexps are fun.";
var result = [Link](pattern, newStr);
[Link](result); // Prints: "Hello Regexps are fun!"
4. ‘replace() with Subexpressions’
- Purpose: Replace portions of a string using back-references to regular
expression groups.
- Example:
var pattern = /(\d{3})(\d{2})(\d{4})/;
var newStr = "$1-$2-$3";
var str = "123456789";
var result = [Link](pattern, newStr);
[Link](result); // Prints: "123-45-6789"

5. ‘match()’
- Purpose: Finds all occurrences of a regular expression in a string and returns
them in an array.
- Example:
var pattern = /\d{2}/g;
var str = "22, 48, 13, 17, 26";
var result = [Link](pattern);
[Link](result); // Prints: ["22", "48", "13", "17", "26"]

- With Global Flag: The result includes an array of all matches.


- With Non-global Flag: It behaves similarly to ‘[Link]()’, returning the
first match along with subexpressions.

var pattern = /(\w+):\/\/([\w\.]+)\/([\w\/]+)/;


var str = "The URL is [Link]
var result = [Link](pattern);
[Link](result);
// result[0] = [Link]
// result[1] = http
// result[2] = [Link]
// result[3] = DOM/Activity

Each of these string methods provides useful ways to handle text based on
regular expressions, offering both matching and manipulation features.

Advanced Regular Expressions

Expected Question :
b) Write a short note on Advanced Regular Expressions.

1. Multiline Matching
- Purpose: The multiline flag (‘m’) allows the characters ‘^’ and ‘$’ to match not
only the beginning and end of the entire string but also the beginning and end of
each line within the string.

- Example 1:
javascript
var str = "Is this all there\nis";
var pattern = /^is/m; // ^ matches the beginning of a line, m flag enables
multiline matching
var result = [Link](pattern);
[Link](result); // Output: ["is"]

Here, ‘^’ matches "is" at the start of the third line, thanks to the ‘m’ flag.

- Example 2:
var str = "This text has multiple lines. \nThis is the second line.\nThe third.";
var pattern = /^.*$/gm; // ^ matches the beginning of a line, $ matches the
end of the line, g flag matches all lines
var result = [Link](pattern);
[Link](result);
// Output:
// ["This text has multiple lines.", "This is the second line.", "The third."]

- This example shows how the ‘m’ flag allows matching entire lines, using ‘^’ to
match the beginning and ‘$’ for the end of each line.
2. Non-Capturing Parentheses
- Purpose: Non-capturing parentheses, written as ‘(?:...)’, are used when you want
to group parts of a regular expression without saving those parts for back
referencing. This can be useful when you do not need to refer back to a part of
the match but still want to group expressions together for clarity.

- Example:
var str = "aaaaaabcd";
var pattern = /(?:a+)(bcd)/; // The non-capturing group (a+) will not be saved
for later reference
var result = [Link](str); // Executes the regular expression
[Link](result[1]); // Output: "bcd"

- In this example, ‘(?:a+)’ does not capture the sequence of "a"s, but the ‘bcd’
part is captured as the first group.

3. Lookaround Groups
- Purpose: Lookaround groups are used to match text only if it is followed or
preceded by a specific pattern, without including the followed or preceded text
in the match. There are four types of lookaround groups:
- Positive Lookahead (‘(?=...)’): Matches a pattern only if it is followed by
another pattern.
- Negative Lookahead (‘(?!...)’): Matches a pattern only if it is not followed by
another pattern.
- Positive Lookbehind (‘(?<=...)’): Matches a pattern only if it is preceded by
another pattern.
- Negative Lookbehind (‘(?<!...)’): Matches a pattern only if it is not preceded by
another pattern.

- Example 1: Positive Lookahead


var str = "123abc456";
var pattern = /\d(?=abc)/; // Matches a digit only if it is followed by "abc"
var result = [Link](pattern);
[Link](result); // Output: ["3"]

- Here, the lookahead ‘(?=abc)’ ensures that the digit "3" is matched only if it
is followed by "abc".

- Example 2: Negative Lookahead


var str = "123abc456";
var pattern = /\d(?!abc)/; // Matches a digit only if it is not followed by "abc"
var result = [Link](pattern);
[Link](result); // Output: ["1", "2", "4", "5", "6"]

- This negative lookahead ensures that digits followed by "abc" are excluded
from the match, leaving digits not followed by "abc" as the matches.

- Example 3: Positive Lookbehind


var str = "abc123def";
var pattern = /(?<=abc)\d/; // Matches a digit only if it is preceded by "abc"
var result = [Link](pattern);
[Link](result); // Output: ["1"]

- The lookbehind ‘(?<=abc)’ ensures that a digit is matched only if it is preceded


by the string "abc". Thus, the digit "1" is matched.

- Example 4: Negative Lookbehind


var str = "abc123def";
var pattern = /(?<!abc)\d/; // Matches a digit only if it is not preceded by
"abc"
var result = [Link](pattern);
[Link](result); // Output: ["2", "3", "1", "2", "3"]

In this example, the negative lookbehind ‘(?<!abc)’ ensures that any digit
preceded by "abc" is excluded. Hence, the digits that are not preceded by "abc"
are matched.
- These advanced techniques allow you to create highly flexible and complex
patterns, providing much more control over string matching and manipulation.

Look ahead and Look Behind :

Expected Question :
1) Explain Look ahead and Look behind concepts in JavaScript.

Lookahead :
- A lookahead group is a non-capturing group that allows you to match a part of
a string only if it is followed by a specific sequence of characters, without
including that sequence in the match itself.
- There are two types of lookaheads: positive lookahead and negative lookahead.

Positive Lookahead (‘?=‘)


- Syntax: ‘(?=...)’
- A positive lookahead ensures that a given expression is followed by a specific
pattern but does not include that pattern in the match.

- Example:
var pattern = /x(?=y)/;
var str = "SCOE-E&TC";
var result = [Link](pattern);
[Link](result); // Output: ["x"]

In this example, the pattern ‘/x(?=y)/’ will match ‘x’ only if it is followed by ‘y’.
The ‘y’ is not included in the match.

Negative Lookahead (‘?!’)


- Syntax: ‘(?!...)’
- A negative lookahead ensures that a given expression is not followed by a
specific pattern. The pattern will not match if it is followed by that sequence.
- Example:
var pattern = /x(?!y)/;
var str = "SCOE-E&TC";
var result = [Link](pattern);

[Link](result); // Output: ["x"]

In this case, the pattern ‘/x(?!y)/’ will match ‘x’ only if it is not followed by ‘y’.
If ‘x’ were followed by ‘y’, the match would not occur.

Both positive and negative lookaheads do not include the pattern inside the
lookahead in the final match; they only assert whether the condition is true or
false.

Lookbehind :

- A lookbehind group is a non-capturing group that allows you to match a part of


a string only if it is preceded by a specific sequence of characters, without
including that preceding sequence in the match itself.
- Similar to lookaheads, there are positive lookbehind and negative lookbehind
assertions.

Positive Lookbehind (‘?<=‘)


- Syntax: ‘(?<=...)’
- A positive lookbehind ensures that a given pattern is preceded by a specific
sequence but does not include that sequence in the match.

- Example:
var pattern = /(?<=x)y/;
var str = "SCOE-E&TC";
var result = [Link](pattern);
[Link](result); // Output: ["y"]
Here, the pattern ‘/y(?<=x)/’ will match ‘y’ only if it is preceded by ‘x’. So, "xy"
would match, but "xx" or "yx" would not.

Negative Lookbehind (‘?<!’)


- Syntax: ‘(?<!...)’
- A negative lookbehind ensures that a given pattern is not preceded by a
specific sequence. The match will not occur if the pattern is preceded by that
sequence.

- Example:
var pattern = /(?<!x)y/;
var str = "SCOE-E&TC";
var result = [Link](pattern);
[Link](result); // Output: ["y"]

- In this case, the pattern ‘/(?<!x)y/’ will match ‘y’ only if it is not preceded by
‘x’. So, "by" would match, but "xy" would not.

- Both positive and negative lookbehind assertions help in determining whether


a match should occur based on the preceding characters, without including those
characters in the match.

Greedy Matching
- Greedy matching means the regular expression tries to match as many
characters as possible.
- The engine looks for the longest possible match and if not found, removes the
last character and reattempts.
- Example:
var pattern = /(ma.*ing)/;
var str = "Regexp matching can be daunting.";
[Link](str);
alert(RegExp.$1);
- The result is "matching can be daunting" because the ‘.*’ quantifier matches
the longest substring possible.

Disabling Greedy Matching


- Non-greedy matching (or lazy matching) matches the shortest possible string.
- This is done by appending a ‘?’ to quantifiers.
- Example:
var pattern = /(ma.*?ing)/;
var str = "Regexp matching can be daunting.";
[Link](str);
alert(RegExp.$1);

- The result will be "matching" because ‘.*?’ matches as little as possible.

Expected Question :
c) What are the limitations of Regular Expression?

Limitations of Regular Expressions


1. Complexity: Some regular expressions have exponential complexity, making
them slow for large datasets.

2. Readability: Complex regex patterns can be hard to understand and maintain.

3. Performance: Regex with excessive backtracking or alternatives can be slow.

4. Real-world Validation:
- Email Addresses: Difficult to validate due to complex formats (e.g., ‘!’ or ‘+’
symbols, IP addresses).
- Phone Numbers: Different formats in various countries make it hard to
validate with regex alone.
- Credit Card Numbers: Regex can check the format, but not the actual validity
(e.g., through Luhn's algorithm).
5. Semantic Validity: Regex can validate the format but not check if the data is
logically correct (e.g., ‘31/02/2021’).

Regular expressions are useful for basic validation, but for more complex
scenarios, additional logic is often required.
Some pyq’s program

Q. Write a program to study string related built-in methods in JavaScript.

JavaScript Program to Study String-Related Built-In Methods

- In this program, we will explore string-related built-in methods in JavaScript.


- JavaScript provides several methods to manipulate and handle strings
effectively.
- These methods allow you to perform various operations such as modifying,
searching, and extracting substrings from strings.

Commonly Used String Methods in JavaScript:

1. ‘charAt(index)’: Returns the character at the specified index in a string.


2. ‘concat(string1, string2, ...)’: Combines two or more strings into a single string.
3. ‘includes(searchString)’: Checks if the string contains the specified substring.
4. ‘indexOf(searchString)’: Returns the first index of the specified substring.
If not found, returns ‘-1’.
5. ‘toUpperCase()’: Converts the entire string to uppercase letters.
6. ‘toLowerCase()’: Converts the entire string to lowercase letters.
7. ‘slice(startIndex, endIndex)’: Extracts a part of the string and returns it as
a new string.
8. ‘replace(searchValue, newValue)’: Replaces a specified value with another value
in a string.
9. ‘trim()’: Removes whitespace from both ends of the string.
10. ‘split(separator)’: Splits the string into an array of substrings based on the
separator provided.
JavaScript Code Example:

// Step 1: Declare a string


let myString = " Hello, JavaScript World! ";

// Step 2: Using charAt() method to get a character at a specific index


[Link]("Character at index 6: " + [Link](6)); // Output: "J"

// Step 3: Using concat() method to combine two strings


let newString = [Link](" Enjoy Learning!");
[Link]("Concatenated String: " + newString);

// Step 4: Using includes() method to check if the string contains a specific


word
[Link]("Does the string contain 'JavaScript'? " +
[Link]("JavaScript")); // Output: true

// Step 5: Using indexOf() method to find the position of the first occurrence
of a substring
[Link]("Index of 'World': " + [Link]("World")); // Output: 19

// Step 6: Using toUpperCase() method to convert string to uppercase


[Link]("Uppercase String: " + [Link]());

// Step 7: Using toLowerCase() method to convert string to lowercase


[Link]("Lowercase String: " + [Link]());

// Step 8: Using slice() method to extract part of the string


let slicedString = [Link](3, 10);
[Link]("Sliced String (from index 3 to 10): " + slicedString); // Output: "llo,
Ja"

// Step 9: Using replace() method to replace part of the string


let replacedString = [Link]("JavaScript", "[Link]");
[Link]("Replaced String: " + replacedString);

// Step 10: Using trim() method to remove whitespaces from both ends of the
string
let trimmedString = [Link]();
[Link]("Trimmed String: '" + trimmedString + "'");

// Step 11: Using split() method to split the string into an array based on a space
let stringArray = [Link](" ");
[Link]("String Split into Array: ", stringArray);

Explanation of Each Method:

1. ‘charAt(index)’:
This method is used to get a character from a string at a specific index. In
our case, ‘[Link](6)’ returns ‘'J'‘ because ‘'J'‘ is the character at
index 6 in the string ‘"Hello, JavaScript World!"‘.

2. ‘concat()’:
The ‘concat()’ method is used to merge two or more strings. Here, the original
string ‘myString’ is concatenated with the string ‘" Enjoy Learning!"‘, producing
a new string: ‘" Hello, JavaScript World! Enjoy Learning!"‘.

3. ‘includes()’:
This method checks if a string contains a specific substring. We check if
‘"JavaScript"‘ is present in ‘myString’. Since it is, the method returns ‘true’.

4. ‘indexOf()’:
The ‘indexOf()’ method returns the index of the first occurrence of a
specified substring. In our case, it returns ‘19’ because the substring ‘"World"‘
starts at index 19.
5. ‘toUpperCase()’:
This method converts all characters in the string to uppercase. For ‘myString’,
it converts ‘" Hello, JavaScript World! "‘ to ‘" HELLO, JAVASCRIPT WORLD!
"‘.

6. ‘toLowerCase()’:
This method converts all characters in the string to lowercase. For ‘myString’,
it converts ‘" Hello, JavaScript World! "‘ to ‘" hello, javascript world! "‘.

7. ‘slice(startIndex, endIndex)’:
The ‘slice()’ method extracts a section of a string. We extract characters
from index ‘3’ to ‘10’, which results in ‘"llo, Ja"‘.

8. ‘replace(searchValue, newValue)’:
The ‘replace()’ method replaces the first occurrence of a substring with
another substring. We replace ‘"JavaScript"‘ with ‘"[Link]"‘, resulting in ‘"
Hello, [Link] World! "‘.

9. ‘trim()’:
This method removes any leading and trailing whitespace from the string.
After trimming, the string ‘" Hello, JavaScript World! "‘ becomes ‘"Hello,
JavaScript World!"‘.

10. ‘split(separator)’:
The ‘split()’ method splits a string into an array of substrings based on the
separator. Here, the string is split into an array of words using ‘" "‘ (space) as
the separator. The resulting array is: ‘["Hello,", "JavaScript", "World!"]’.

Output:

Character at index 6: J
Concatenated String: Hello, JavaScript World! Enjoy Learning!
Does the string contain 'JavaScript'? true
Index of 'World': 19
Uppercase String: HELLO, JAVASCRIPT WORLD!
Lowercase String: hello, javascript world!
Sliced String (from index 3 to 10): llo, Ja
Replaced String: Hello, [Link] World!
Trimmed String: 'Hello, JavaScript World!'
String Split into Array: [ 'Hello,', 'JavaScript', 'World!' ]
Unit-5: Fundamental Client-Side JavaScript and Event Handling

Expected question :
-> Define JavaScript object model and explain four distinct object models used
in JavaScript.
-> Explain event and event handler with an example.
-> Write a JavaScript program to create a Home page of any website and
change background color using.
On mouse over event (mouse over)
On focus event (focus)

-> Describe Document properties and methods with their HTML relationship.
-> Differentiate between HTML and DHTML.
-> Explain DOM and CSS Elements with example.

-> Describe Netscape 4 Event Model in detail.


-> Explain the role of Event Handlers in Java Script.
-> Write short note on DOM and Document Tree Elements.

-> What is Document Tree? Explain DOM Methods to Create Nodes.


-> Elaborate how DOM standard is supported by today’s browsers is CSS.
-> Explain DOM2 Event Model.
Introduction
- In JavaScript, there are two main object models that provide access to various
aspects of the browser and the document. These object models are:

1. Browser Object Model (BOM):


- The Browser Object Model allows JavaScript to interact with the browser
window and other browser-related features.
- It provides access to browser characteristics like:
- Window: Represents the browser window itself.
- Navigator: Provides information about the browser, such as its name and
version.
- Location: Allows access to the URL of the page.
- History: Enables navigation through the browser’s history (back, forward).
- Screen: Provides information about the user's screen, such as its resolution.

2. Document Object Model (DOM):


- The Document Object Model focuses on the contents of the browser window,
specifically the web page (document) being displayed.
- It allows JavaScript to interact with and manipulate the structure and
content of a web page.
- The DOM represents the document as a tree structure where each node
corresponds to an HTML element, attribute, or piece of text.
- Through the DOM, JavaScript can:
- Access and modify elements (e.g., paragraphs, images, forms).
- Change the content of the page (e.g., adding text, changing images).
- Modify the structure (e.g., adding or removing HTML elements).

Object Model

Expected Question :
1) Define JavaScript object model and explain four distinct object models
- JavaScript interacts with various parts of the browser and document through
several layers of objects. These are divided into categories:

1. Core JavaScript Language:


- This is the basic structure of JavaScript, including:
- Data Types: Defines the types of values, such as numbers, strings, booleans,
and objects.
- Operators: Include arithmetic operators (e.g., +, -, *, /), comparison
operators (e.g., ==, ===), logical operators (e.g., &&, ||), etc.
- Statements: Control the flow of the program (e.g., if-else, loops).
- Functions: Encapsulated blocks of code that can be executed when called.

2. Built-in Objects:
- JavaScript provides built-in objects that help manage data and other tasks.
These include:
- Math: Provides mathematical constants and functions (e.g., [Link],
[Link]()).
- String: Offers methods for string manipulation (e.g., ‘toUpperCase()’,
‘substring()’).
- Number: Used for handling numerical values.
- Array: A collection of values indexed by numbers, with methods to
manipulate them.
- Date: For working with dates and times.
- RegExp: Provides regular expression functionality for pattern matching.

3. Browser Object Model (BOM):


- The BOM provides objects that help interact with the browser and its
environment. These include:
- Window: Represents the entire browser window, providing methods for
controlling the window, such as opening new tabs or resizing the window.
- Navigator: Provides information about the browser, such as its name,
version, and capabilities.
- Location: Allows access to the current URL of the page and methods to
change it (e.g., ‘[Link]’).
- History: Provides methods to navigate through the browser’s history (e.g.,
‘[Link]()’ and ‘[Link]()’).
- Screen: Gives information about the user’s screen, like screen width and
height.

4. Document Object Model (DOM):


- The DOM represents the structure of the HTML document and is essential
for web page manipulation. It allows JavaScript to:
- Access Elements: JavaScript can access and modify HTML elements on the
page (e.g., by using ‘[Link]()’ or ‘[Link]()’).
- Modify Content: JavaScript can change the text, images, and other content
on the page.
- Manipulate Structure: JavaScript can add, remove, or rearrange HTML
elements using methods like ‘appendChild()’, ‘removeChild()’, or ‘createElement()’.

Evolution of JavaScript Object Models


- Over time, JavaScript has seen several versions of object models, each
offering more advanced features:

1. Traditional JavaScript Object Model (Netscape 2, Internet Explorer 3):


- The first version of JavaScript, where basic document manipulation and
browser interactions were introduced.

2. Extended JavaScript Object Model (Netscape 3):


- The basis of DOM Level 0, providing more functionality for document
manipulation, such as dynamic interactions with HTML elements.

3. Dynamic HTML (DHTML) Flavored Object Models:


- This version, used in Internet Explorer 4.x and Netscape 4.x, introduced the
concept of dynamically changing HTML elements, enabling animations and page
updates without reloading the page.
4. Extended Browser Object Model + Standard DOM:
- Modern browsers support both the Browser Object Model (BOM) and
Document Object Model (DOM).
- This standardization allows for the consistent manipulation of both the
browser environment and the document’s contents.

Traditional/Initial JavaScript Object Model


- The initial JavaScript object model, introduced in Netscape 2, was created to
manipulate basic browser features and form content before sending data to
server-side programs.
- It was a simple approach, focused on the browser and document objects.

Features of the Initial Object Model:


- Primary Goal: The main purpose was to check or manipulate forms before
submitting them to the server.
- Simple Tasks: It was limited to simple tasks like interacting with forms and
basic browser properties.

Important Objects in the Initial JavaScript Object Model:

1. Window Object:
- Represents the entire browser window.
- It allows interaction with the browser, like showing alerts or opening new
windows.
- Example: ‘[Link]("Hello")’. In JavaScript, we usually write it as
‘alert("Hello")’, but it refers to the ‘window’ object by default.

2. document Object:
- Contains all the elements of the webpage, like buttons, text boxes, and other
HTML content.
- JavaScript can interact with these elements to read or change the content
on the page.
3. frames[] Object:
- If the page contains multiple frames (like in a frameset), this object holds
references to each frame in an array.
- Each frame is a separate ‘Window’ object that can also have its own content.

4. history Object:
- Tracks the page history (the URLs the user has visited).
- Methods like ‘[Link]()’ or ‘[Link]()’ allow you to move through
the history of visited pages.

5. location Object:
- Represents the URL of the current page.
- Allows you to retrieve or modify the URL (e.g., ‘[Link] =
"[Link] to change the page).

6. navigator Object:
- Provides information about the browser, like its name and version.
- Can be used to check if certain features (such as cookies) are supported by
the browser.

How the Objects Work Together:


- For instance, when you use ‘alert("Hello World!")’, it is actually invoking the
‘alert()’ method of the ‘Window’ object.
- JavaScript assumes the use of the ‘window’ object, so you can simply write
‘alert("Hello World!")’ without explicitly mentioning ‘window’.

Basic Example:
// Using the window object to show an alert
[Link]("This is a message"); // This is the same as just writing:
alert("This is a message"); // JavaScript assumes it's using the window object.

Limitations of the Initial Object Model:


- This early version was designed for basic interactions and didn’t include
features necessary for more complex applications, such as advanced event
handling or dynamic content updates.

Document Object

- The Document object provides access to various elements within the web page,
such as anchors, form fields, links, and page properties like background color
and text color.
- It allows JavaScript to interact with the structure and content of the
webpage.
- However, the structure of the Document object can differ significantly
between different browsers and versions.

Document Properties:

Pyq’s Question :
1) Describe Document properties and methods with their HTML
relationship.

- alinkColor: The color of active links (links clicked by the user), typically red by
default

- anchors[]: An array of all the anchor elements (‘<a>‘) in the document.

- bgColor: The background color of the page.

- cookie: The string that gives access to the page's cookies.

- fgColor: The color of the document’s text (foreground color).

- forms[]: An array containing all the form elements (‘<form>‘) in the document.

- links[]: An array of all the link elements (‘<a href="URL">‘) in the document.
- linkColor: The color of unvisited links, typically blue by default.

- location: The URL of the current document (deprecated in favor of


‘[Link]’ or the ‘Location’ object).

- lastModified: A string containing the date when the document was last
modified.

- title: The title of the document (shown in the browser tab).

- vlinkColor: The color of visited links, typically purple by default.

Methods Available for Document:


- close(): Closes the input stream to the document.
- open(): Opens the document for input.
- write(): Writes text or HTML directly to the document.
- writeln(): Writes text or HTML followed by a newline.

Early Limitations of the Document Object Model:


In the initial Document Object Model:
- Only document-wide properties, links, anchors, and forms could be directly
accessed.
- There was no support for manipulating text, images, applets, or embedded
objects.
- It didn't allow access to the presentation properties (such as styles) of most
elements.

Example of Document Properties and Methods:

[Link]("Location = " + [Link] + "<br>");


[Link]("URL = " + [Link] + "<br>");
[Link]("Title = " + [Link] + "<br>");
[Link]("Last Modification Date = " + [Link] + "<br>");
[Link]("Background Color = " + [Link] + "<br>");
[Link]("Text Color = " + [Link] + "<br>");
[Link]("Link Color = " + [Link] + "<br>");
[Link]("Active Link Color = " + [Link] + "<br>");
[Link]("Visited Link Color = " + [Link] + "<br>");

if ([Link] > 0) {
[Link]("<h2>Links</h2>");
[Link]("# Links = " + [Link] + "<br>");
for (var i = 0; i < [Link]; i++) {
[Link]("Links[" + i + "] = " + [Link][i] + "<br>");
}
}

if ([Link] > 0) {
[Link]("<h2>Anchors</h2>");
[Link]("# Anchors = " + [Link] + "<br>");
for (var i = 0; i < [Link]; i++) {
[Link]("Anchors[" + i + "] = " + [Link][i] + "<br>");
}
}

if ([Link] > 0) {
[Link]("<h2>Forms</h2>");
[Link]("# Forms = " + [Link] + "<br>");
for (var i = 0; i < [Link]; i++) {
[Link]("Forms[" + i + "] = " + [Link][i].name + "<br>");
}
}

- Many of these properties will not be set unless you run the script on a document
containing specific elements (forms, links, etc.).
- For example, if no ‘<form>‘ is present in the document, the ‘forms[]’ property
will be empty.
- Browsers may define default values for certain properties like text and link
colors, even if the corresponding HTML elements or attributes are not present.

Accessing Document Elements by Positions


- Initially, browsers supported a limited set of elements for scripting, but
modern browsers allow you to access virtually any HTML element.
- The traditional JavaScript object model provides a way to access (X)HTML
elements by their position in the document.

- Accessing a ‘<form>‘ Tag:


You can access a form element in the document using the following syntax:
[Link][formIndex]

- Here, ‘formIndex’ is an integer (e.g., 0, 1, 2, ...) representing the position of


the form in the document.

- Accessing Form Elements:


To access specific form elements (like inputs, checkboxes, etc.), use the
following:
[Link][formIndex].elements[elementIndex]

- This allows you to target specific elements within a form based on their
position.

- Downside:
The major downside of using position-based access is that if the order of the
elements or forms changes in the document, the JavaScript code may break or
reference the wrong element. A more robust approach is to use names instead
of positions.

Accessing Document Elements by Name


- To make markup elements easily accessible for scripting, elements should be
given unique identifiers using the ‘id’ or ‘name’ attribute.

- Using ‘id’ for Identification:


HTML elements can be assigned an ‘id’ attribute, which allows them to be
accessed directly in JavaScript. For example:

<b id="vimp">This is very important.</b>

In JavaScript, you can access it like this:


[Link]("vimp")

Using ‘name’ for Compatibility:


- In earlier versions of HTML, the ‘name’ attribute was used to identify
elements.
- Even today, the ‘name’ attribute is commonly used for certain elements like
‘<form>‘, ‘<input>‘, ‘<button>‘, etc., for backward compatibility.

For example:

<form name="myForm" id="myForm" method="get" action="#">


<input type="text" name="userName" id="userName" />
</form>

In JavaScript, you can access the form using:


[Link]

And access the input element using:


[Link]

Accessing Objects Using Associative Arrays

- Many arrays in the Document object are associative, which means elements can
be accessed using names instead of numerical indices.

Accessing Elements Using ‘name’ or ‘id’:


- You can use either the ‘name’ or ‘id’ attribute of an element to access it.
- For example, if a form is named ‘myForm2’ and contains an input field named
‘user’, you can access the form and its elements using the following:

<form name="myForm2" id="myForm2" method="get" action="#">


<input name="user" type="text" value="" />
</form>

In JavaScript, access the form:


[Link]["myForm2"]

And access the input element:


[Link]["myForm2"].elements["user"]

Internet Explorer's Collections:


- Internet Explorer extends the associative arrays by referring to them as
collections.
- Collections can be indexed either by an integer or a string, and they can also
be accessed using the ‘item()’ method.

Example:
[Link]("myForm2")

- This approach allows for more flexible and readable code compared to position-
based access.
Event Handlers

Expected Question :
1) Explain event and event handler with an example.

- Event handlers are the primary way in which JavaScript responds to user
actions, such as clicks or mouse movements.
- An event handler is a piece of JavaScript code associated with a specific part
of the document and a particular event.
- The code is triggered when the event occurs at that part of the document.

Common events include:


Click: When the user clicks on an element.
MouseOver: When the user places the mouse over an element.
MouseOut: When the user moves the mouse away from an element.

- These events are commonly used with form buttons, form fields, images, and
links.
- They are used for tasks like form validation and rollover effects for buttons.

- Not every object can handle every type of event. The types of events an object
can handle are typically linked to how that object is commonly used.

Example: Button Click Event

Here’s an example where a button click triggers an alert:

<form method="get" action="#">


<input type="button" value="Click me" onclick="alert('That tickles!');"/>
</form>

- When the user clicks the button, the browser sends a ‘Click’ event to the
button object, and its ‘onclick’ event handler is triggered.
- This is part of the Event Model in JavaScript, which defines how events are
handled and how event handlers are attached to objects.

Using Pure JavaScript for Event Handlers


- Instead of using HTML attributes like ‘onclick’ directly in markup, you can also
attach event handlers using JavaScript:

<form name="myForm" id="myForm" method="get" action="#">


<input name="myButton" id="myButton" type="button" value="Click me"/>
</form>

<script type="text/javascript">
[Link] = new Function("alert('That tickles!')");
</script>

- In this example, an anonymous function is assigned to the ‘onclick’ property of


the ‘myButton’ element.
- This approach allows more flexibility and avoids cluttering the HTML with inline
JavaScript.

Triggering Events Programmatically

- You can also trigger events programmatically using JavaScript. For example,
you can call the ‘click()’ method on a button to trigger its ‘onclick’ event handler:

[Link]();

This will cause the same event to occur as if the user clicked the button.
Object Models and Evolution
- Over time, browser vendors have extended the functionality of the Document
Object Model (DOM).
- As new versions of browsers were released, additional features were added,
bugs were fixed, and the document's capabilities were enhanced.

- While the gradual evolution of the DOM allows for more powerful tasks, it
also introduces challenges for web developers.
- The biggest issue arises from the fact that different browsers developed
their object models in different ways.
- For example, Internet Explorer and Netscape introduced proprietary tags and
non-standard methods for handling Dynamic HTML (DHTML), which means that
DHTML code written for one browser often doesn't work on the other.

- This created compatibility problems for web developers who had to write
separate code for different browsers.
- However, as modern browsers have improved their support for DOM standards,
these differences have become less of an issue, making it easier for developers
to write cross-browser compatible code.

Early Netscape Browsers

Netscape 2: Basic Object Model


- Netscape 2 was the first browser to introduce JavaScript and its associated
object model, though its capabilities were very basic.
- The primary use of JavaScript in this version was for form validation and
simple page manipulation, like displaying the last date the document was
modified.
- The object model was limited to basic functionality, focusing mainly on
interacting with forms.
Netscape 3: Primitive DHTML Support
- Netscape 3 expanded the capabilities of the object model, enabling the
creation of primitive DHTML (Dynamic HTML) applications.
- It allowed scripts to access more parts of the document content, including
embedded objects, applets, plugins, and images.
- This version introduced several important object properties that paved the
way for more interactive web pages. Here are some key objects and properties:

- Objects:
- ‘button’, ‘checkbox’, ‘anchors[]’, ‘applets[]’, ‘file’, ‘hidden’, ‘embeds[]’,
‘password’, ‘forms[]’, ‘elements[]’, ‘radio’, ‘images[]’, ‘reset’, ‘links[]’, ‘select[]’,
‘option[]’, ‘plugins[]’, ‘submit’, ‘text’.

- New Document Properties in Netscape 3:


- applets[]: Array of ‘<applet>‘ tags in the document.
- embeds[]: Array of ‘<embed>‘ tags in the document.
- images[]: Array of ‘<img>‘ tags in the document.
- plugins[]: Array of plug-ins in the document.

These additions marked the beginning of richer, more interactive web


experiences, though still limited compared to modern DHTML.

Netscape 4: DHTML-Oriented Object Model


- Netscape 4 represented a significant leap forward in web development,
introducing robust support for Dynamic HTML (DHTML), which enabled
interactive and dynamic content updates without requiring page reloads.
- Key features of the Netscape 4 object model include:
- Support for the ‘<layer>‘ tag: This was a proprietary feature that allowed for
more complex layering of content on the page, helping to create interactive, non-
liner page layouts.
- Expanded event model: Netscape 4 added more advanced event handling,
enabling more sophisticated user interactions.
- Style objects: Netscape 4 introduced the ability to manipulate CSS styles
directly from JavaScript, paving the way for real-time style changes.

- Netscape 4 Object Model:


- ‘anchors[]’, ‘applets[]’, ‘classes[]’, ‘embeds[]’, ‘forms[]’, ‘ids[]’, ‘document’,
‘images[]’, ‘links[]’, ‘layers[]’, ‘plugins[]’, ‘tags[]’.

- New Document Properties in Netscape 4:


- classes[]: Accesses or creates CSS styles for elements with a specified class
attribute.
- ids[]: Accesses or creates CSS styles for elements with a specified ‘id’
attribute.
- layers[]: Array of ‘<layer>‘ tags or positioned ‘<div>‘ elements. Indexed by z-
index, with 0 being the bottommost layer.
- tags[]: Accesses or creates CSS styles for arbitrary HTML elements.

The introduction of DHTML in Netscape 4 laid the groundwork for modern web
development techniques, allowing for more dynamic, responsive, and interactive
web pages.

Internet Explorer 3: Basic Object Model

- Internet Explorer 3 introduced a basic object model, which is similar to the


lowest common denominator approach.
- It provided a limited but functional set of properties for the Document object,
with a few additional features compared to Netscape 2.
- These additions enabled more flexibility in dealing with web pages.

IE3 Object Model


- The IE3 object model includes several properties that provide access to HTML
elements in a document, such as buttons, forms, and links. Some important
features of this model are:
- Properties in IE3:
- button: Represents button elements (‘<button>‘).
- checkbox: Represents checkbox elements (‘<input type="checkbox">‘).
- hidden: Represents hidden input elements (‘<input type="hidden">‘).
- password: Represents password input elements (‘<input type="password">‘).
- anchors[]: Array of anchor (‘<a>‘) elements in the document.
- radio: Represents radio button elements (‘<input type="radio">‘).
- forms[]: Array of ‘<form>‘ elements in the document.
- elements[]: Array of all form elements in the document (e.g., ‘<input>‘,
‘<select>‘).
- document: Represents the document object itself.
- reset: Represents reset buttons (‘<input type="reset">‘).
- frames[]: Array of frame objects for ‘<frame>‘ and ‘<iframe>‘ elements.
- select: Represents ‘<select>‘ elements (dropdown lists).
- option: Represents ‘<option>‘ elements within a ‘<select>‘ element.
- links[]: Array of all ‘<a>‘ links in the document.
- submit: Represents submit buttons (‘<input type="submit">‘).
- text: Represents ‘<input type="text">‘ elements.
- textarea: Represents ‘<textarea>‘ elements.

This model was basic but functional for its time, supporting simple web
interactions like form handling and link navigation.

Internet Explorer 4: DHTML Object Model

- Internet Explorer 4 significantly improved the object model, making it more


suitable for creating Dynamic HTML (DHTML) applications.
- The key innovation in IE4 was the full representation of every HTML element
as an object.
- This was a major leap forward compared to previous versions, which only
exposed specific elements like forms and links.
- IE4's model was similar to Netscape 4 but was not compatible with it, which
created challenges for developers working cross-browser.
IE4 Object Model
- The IE4 model introduced new features, including a more complete set of
properties that enabled developers to manipulate more aspects of the web page
dynamically.

- Properties in IE4:
- all[]: Array of all HTML tags in the document (new to IE4).
- applets[]: Array of ‘<applet>‘ tags in the document.
- children[]: Array of all child elements of a specific object.
- embeds[]: Array of embedded objects (‘<embed>‘ tags).
- images[]: Array of ‘<img>‘ tags in the document.
- scripts[]: Array of ‘<script>‘ tags in the document.
- styleSheets[]: Array of ‘<style>‘ tags or CSS style objects in the document.

Key Enhancements:
- IE4 made it possible to access every HTML element, such as ‘<div>‘, ‘<span>‘, and
others, as objects within the JavaScript environment.
- It also introduced the ability to manipulate the page's CSS styles directly via
JavaScript, giving developers much more control over the document's
presentation and layout.
- The ‘styleSheets[]’ property allowed access to the stylesheets directly, making
it easier to modify styles dynamically.

Standard Document Object Model (DOM)


- The Document Object Model (DOM) is a standardized way to represent a web
page's structure so that JavaScript can interact with it across different
browsers.
- Before the DOM, different browsers had their own object models (like
Netscape's and Internet Explorer's), which led to compatibility issues for
developers.
- To solve this, the W3C (World Wide Web Consortium) created the DOM to
ensure that web pages can be accessed and manipulated in a consistent way
across all browsers.
- The DOM provides a programming interface (API) that allows access to a web
page's structure, including its tags, attributes, styles, and content, using
programming languages like JavaScript.
- With the DOM, web developers can read and modify the content and structure
of a webpage dynamically.

DOM Levels

- The DOM is divided into several levels, each offering different features and
improvements over the previous version.

DOM Level 0
- This level is similar to the older object models used by Netscape 3.0 and
Internet Explorer 3.0.
- It supports basic document object collections like forms[], images[], anchors[],
links[], and applets[].
- This level is often referred to as the classic or traditional JavaScript object
model.

DOM Level 1 :
- This level allows developers to manipulate all elements in a document using a
common set of functions.
- It provides cross-browser compatibility, which was missing in earlier versions.
- In DOM Level 1, the page elements can be read and written at all times,
enabling dynamic changes to the web page.

DOM Level 2 :
- This level builds on DOM Level 1 by adding support for style sheet manipulation
and a more advanced event model.
- It also includes traversal and range operations, which allow more sophisticated
ways of navigating and modifying the document.
- Although it includes many useful features, not all browsers fully support the
features of DOM Level 2.
DOM Categories

The DOM specification divides the functionality into five main categories:

1. DOM Core:
- Defines a generic model for viewing and manipulating a document as a tree
structure.
- This is the base for all other DOM specifications.

2. DOM HTML:
- This is an extension to the core DOM for HTML documents.
- It allows manipulation of HTML elements and is similar to the traditional
JavaScript object model.
- It includes DOM Level 0 features plus the ability to manipulate all HTML
element objects.

3. DOM CSS:
- Provides interfaces to manipulate CSS rules programmatically.
- This allows JavaScript to change styles of elements dynamically.

4. DOM Events:
- Adds event handling to the DOM.
- Events range from user interface actions like mouse clicks to internal DOM-
specific events that occur when the document structure changes.

5. DOM XML:
- Extends the core DOM to work with XML documents.
- It handles specific needs for XML, such as CDATA sections, processing
instructions, and namespaces.

DOM Feature Support Testing

- The DOM specification also includes a way to check if a certain feature is


supported by the browser.
- You can test this using the ‘[Link]()’ method.

Example code to test DOM feature support:

<!DOCTYPE html>
<html>
<head>
<title>DOM Implementation Test</title>
</head>
<body>
<h1>DOM Feature Support</h1>
<hr />
<script type="text/javascript">
var featureArray = ["HTML", "XML", "Core", "CSS2", "Events", "UIEvents",
"MouseEvents", "Traversal"];
var versionArray = ["1.0", "1.0", "2.0", "2.0", "2.0", "2.0", "2.0", "2.0"];
for(i=0; i<[Link]; i++){
var feature = featureArray[i];
var version = versionArray[i];
if([Link] && [Link]){
[Link](feature + " " + [Link](feature,
version));
[Link]("<br />");
}
}
</script>
</body>
</html>

- This script tests which features of the DOM are supported by the browser,
printing out the results for each feature.
- The ‘hasFeature()’ method checks whether a particular feature (like "HTML"
or "CSS2") is available in the current browser version.

- With the DOM standard, web developers can build more powerful, flexible, and
cross-browser-compatible websites and web applications.

Document Trees :

Pyq’s question :
1) What is Document Tree? Explain DOM Methods to Create Nodes.

- In DOM Level 1 and Level 2, the most important concept is that we are
manipulating a document tree.
- This tree structure represents the entire document as a hierarchical set of
nodes, where each node corresponds to a part of the document, such as
elements, attributes, or text.

Consider the following simple HTML document:

<!DOCTYPE html>
<html>
<head></head>
<title>DOM Test</title>
<body>
<h1>DOM Test Heading</h1>
<hr />
<p>A paragraph of <em>text</em> is just an example</p>
<ul>
<li><a href="[Link]
</ul>
</body>
</html>

- When a browser reads this document, it converts it into a tree-like structure


called a DOM tree.
- Each part of the document is represented as a node in the tree. The root of
the tree is typically the ‘<html>‘ element, and each nested element forms a
branch of the tree.

DOM Nodes Related to HTML Documents

- There are several types of nodes in the DOM that relate to HTML or XML
documents:

1. Element Node (Type 1): Represents an element in the document, like ‘<html>‘,
‘<head>‘, ‘<body>‘, ‘<h1>‘, etc.
2. Attribute Node (Type 2): Represents an attribute of an element, such as
‘href="[Link] in an ‘<a>‘ tag.
3. Text Node (Type 3): Represents the actual text content inside an element.
For example, the text inside ‘<h1>DOM Test Heading</h1>‘ is a text node.
4. Comment Node (Type 8): Represents an HTML comment, like ‘<!-- This is a
comment -->‘.
5. Document Node (Type 9): The root node of the DOM tree, which represents
the entire document (typically the ‘<html>‘ element in an HTML document).
6. Document Type Node (Type 10): Represents the document type declaration
(like ‘<!DOCTYPE html>‘).

Example of Document Tree

In the document provided above, the tree would look something like this:
Root Node: <html>
|
|-- <head>
|-- <title>DOM Test</title>
|-- <body>
|-- <h1>DOM Test Heading</h1>
|-- <hr />
|-- <p>A paragraph of <em>text</em> is just an example</p>
|-- <ul>
|-- <li><a href="[Link]
</ul>

Subtrees
- A subtree is any part of the DOM tree that is rooted at a specific node. For
example, consider this HTML fragment:

<p>A paragraph of <em>text</em> is just an example</p>

In this case, the ‘<p>‘ element is the parent of three child nodes:
- The first text node ("A paragraph of ")
- The second element node (‘<em>‘) which contains its own text node ("text")
- The third text node ("is just an example")

This part of the document is a subtree rooted at the ‘<p>‘ element.

Node Relationships
- In a DOM tree, nodes are related to one another in various ways:

- Parent: A node that contains other nodes.


- Child: A node that is contained within another node.
- Sibling: Nodes that share the same parent.
For example, in the ‘<p>‘ element above:
- The parent of the text nodes and ‘<em>‘ is the ‘<p>‘ element.
- The children of the ‘<p>‘ element are the two text nodes and the ‘<em>‘ element.
- The siblings of the ‘<em>‘ element are the text nodes before and after it.

Accessing Elements
- When navigating through an HTML document tree, you can start from the root
or choose any specific element as the starting point.
- In the document below, the ‘<p>‘ tag can be uniquely identified using the ‘id’
attribute with the value ‘p1’:

<!DOCTYPE html>
<html>
<head>
<title>DOM Test</title>
</head>
<body>
<p id="p1" align="center">A paragraph of <em>text</em> is just an example</p>
</body>
</html>

To access the ‘<p>‘ element, you can use:

[Link]('p1');

- This method returns a DOM element object representing the ‘<p>‘ tag. To
examine the object returned, you can use the following JavaScript:

var currentElement = [Link]('p1');


var msg = "nodeName: " + [Link];
msg += "\nnodeType: " + [Link];
msg += "\nnodeValue: " + [Link];
alert(msg);

DOM Node Properties

Here are some of the important properties of DOM nodes:

- nodeName: Contains the name of the node (e.g., "P" for a ‘<p>‘ tag).
- nodeValue: Contains the value within the node. This is generally only applicable
to text nodes.
- nodeType: Holds a number corresponding to the type of the node (e.g., ‘1’ for
element nodes, ‘3’ for text nodes).
- parentNode: Reference to the parent node, if one exists.
- childNodes: A list of child nodes.
- firstChild: The first child node of the element.
- lastChild: The last child node of the element.
- previousSibling: The previous sibling of the node.
- nextSibling: The next sibling of the node.
- attributes: A list of attributes for the element.
- ownerDocument: Points to the HTML document object that contains the
element.

Browser Differences :
- Different browsers may represent the document tree slightly differently.
- For example, browsers like Opera, Netscape, and Mozilla-based browsers
include more nodes in the tree compared to Internet Explorer because
whitespace is also treated as a text node in these browsers.
- While this could cause differences in tree traversal, normalizing the Mozilla-
style DOM tree is possible but generally unnecessary for most use cases.
Other Access Properties
- While ‘getElementById()’ is commonly used, there are other methods useful
for accessing elements:

- getElementsByName(): This method retrieves elements by their ‘name’


attribute. It's commonly used for elements like ‘<form>‘, ‘<input>‘, and ‘<a>‘. For
example:

var tagList = [Link]('myTag');


for (var i = 0; i < [Link]; i++) {
alert(tagList[i].nodeName);
}

Common Tree Traversal Starting Points

In some cases, you may want to start at the top of the document tree and
traverse down. Two useful properties for tree traversal are:

- [Link]: This points to the root element of the document,


typically the ‘<html>‘ tag.
- [Link]: This points to the ‘<body>‘ element.

- Additionally, [Link] can be used to access the document type


definition (DOCTYPE), though it is not modifiable.

DOM Level 0: Traditional JavaScript Collections

- For backward compatibility, DOM Level 0 collections are supported.


- These collections represent object groups that were popular in early browser
versions, and you can access them by index, name, or directly:

- [Link][]: A collection of all anchor tags in the document.


- [Link][]: A collection of all applets.
- [Link][]: A collection of all form tags.
- [Link][]: A collection of all image tags.
- [Link][]: A collection of all link tags.

Generalized Element Collections


- Another way to access elements is through the ‘getElementsByTagName()’
method.
- This method retrieves all elements of a specified tag type. For example, to
retrieve all ‘<p>‘ tags:

var allParagraphs = [Link]('p');

To find all paragraphs within a specific section like ‘<body>‘:

var allParagraphs = [Link]('p');

- Similarly, you can find elements within other elements. For example, to find all
‘<em>‘ tags inside a specific paragraph with the ID ‘p1’:

var para1 = [Link]('p1');


var emElements = [Link]('em');

Creating Nodes
- The DOM provides several methods to create new nodes, which can be added
to the document tree.
- These methods are part of the ‘Document’ object and are used to create
elements, attributes, comments, and text nodes.
- createAttribute(name): Creates an attribute with the specified ‘name’.
Example:
var myAlign = [Link]("align");

- createComment(string): Creates an HTML/XML comment node containing the


specified string.

Example:
var myComment = [Link]("Just a comment");

- createDocumentFragment(): Creates an empty document fragment. It is useful


for holding a collection of nodes that can be added to the document later.

Example:
var myFragment = [Link]();

- createElement(tagName): Creates an element of the specified ‘tagName’.

Example:
var myHeading = [Link]("h1");

- createTextNode(string): Creates a text node containing the specified string.

Example:
var newText = [Link]("Some new text");

Inserting and Appending Nodes

- Once nodes are created, they need to be inserted into the document tree.
- This can be done using the ‘insertBefore()’ and ‘appendChild()’ methods.

appendChild(newChild):
- This method is invoked on the node to which you want to append a child. It adds
‘newChild’ to the end of the list of children of the parent node.
Example:
var newNode = [Link]('b');
var newText = [Link]("Something to add!");
[Link](newText);

This would create the following HTML structure:

<b>Something to add!</b>

You can then append it to an existing node:


var current = [Link]('p1');
[Link](newNode);

insertBefore(newChild, referenceChild):
- This method allows you to insert ‘newChild’ before a specific ‘referenceChild’.

Example of usage:
var newNode = [Link]('b');
var newText = [Link]("Something to add!");
[Link](newText);

var parentNode = [Link]('parent');


var referenceChild = [Link]('referenceChild');
[Link](newNode, referenceChild);

Copying Nodes
- To copy an existing node, you can use the ‘cloneNode()’ method.
- This method takes a single Boolean argument that determines if the copied
node should include all of its child nodes (deep clone) or just the element itself
(shallow clone).
- cloneNode(deep): Creates a copy of the node. If ‘deep’ is ‘true’, it copies all
child nodes; if ‘false’, it only copies the node itself.

Example of cloning and inserting nodes:

<!DOCTYPE html>
<html>
<head>
<title>Clone Demo</title>
</head>
<body>
<p id="pl">This is a paragraph for cloning <hr>More content</p>
<div id="inserthere" style="background-color: yellow;"></div>

<script type="text/javascript">
function cloneAndCopy(nodeId, deep) {
var toClone = [Link](nodeId);
var clonedNode = [Link](deep);
var insertPoint = [Link]('inserthere');
[Link](clonedNode);
}
</script>

<form action="#" method="get">


<input type="button" value="Clone" onclick="cloneAndCopy('pl', false);">
<br>
<input type="button" value="CloneDeep" onclick="cloneAndCopy('pl', true);">
</form>

</body>
</html>
- In this example, when you click the "Clone" button, it clones the ‘<p>‘ tag without
its children, and when you click the "CloneDeep" button, it clones the ‘<p>‘ tag
along with its children.
- The cloned node is then appended to the ‘<div>‘ with the ID ‘inserthere’.

Deleting and Replacing Nodes


- Sometimes you may need to remove or replace nodes in the DOM. The
‘removeChild()’ and ‘replaceChild()’ methods are used for these tasks.

- removeChild(child): This method removes the specified child node from the
DOM. It returns the removed node.

Example of removing the last child of a node:


var lostChild = [Link]([Link]);

- replaceChild(newChild, oldChild): This method replaces ‘oldChild’ with


‘newChild’. Be cautious when using this method because it destroys the contents
of ‘oldChild’.

Example:
var newNode = [Link]("strong");
var newText = [Link]("strong element");
[Link](newText);

var replace = [Link]("toReplace");


if (replace) {
[Link](newNode, replace);
}

- In this example, the ‘<em>‘ element is replaced by a ‘<strong>‘ element containing


the text "strong element."
Modifying Text Nodes
- To modify a text node, you cannot directly change the element itself, but you
can modify its content through the text node.

- Accessing a text node: You can access the text node within an element using
the ‘firstChild’ property of the element.

Example:
var textNode = [Link]('p1').firstChild;

- Modifying the text content: You can use the ‘data’ property of the text node
to change its content.

Example:
[Link] = "I've been changed!";

DOM Methods for Text Nodes

DOM Level 1 provides several methods to manipulate text nodes:

- appendData(string): Appends the specified string to the text node.


- deleteData(offset, count): Deletes ‘count’ characters starting from the
position specified by ‘offset’.
- insertData(offset, string): Inserts the specified string at the given position in
the text node.
- replaceData(offset, count, string): Replaces ‘count’ characters starting from
‘offset’ with the specified string.
- splitText(offset): Splits the text node into two at the specified offset. It
creates a new text node containing the right portion of the text.
- substringData(offset, count): Returns a substring starting at ‘offset’ with the
specified ‘count’ of characters.
Example of Text Node Modifications

<!DOCTYPE html>
<html>
<head>
<title>Text Node Modifications</title>
</head>
<body>
<p id="p1">This is a test</p>
<script type="text/javascript">
var textNode = [Link]('p1').firstChild;
</script>

<form action="#" method="get">


<input type="button" value="Show Data" onclick="alert([Link]);" />
<input type="button" value="Length" onclick="alert([Link]);" />
<input type="button" value="Change" onclick="[Link] = 'New value!';"
/>
<input type="button" value="Append" onclick="[Link](' added
to the end');" />
<input type="button" value="Insert" onclick="[Link](0, 'added
to the front ');" />
<input type="button" value="Substring"
onclick="alert([Link](2, 2));" />
<input type="button" value="Split" onclick="var temp = [Link](5);
alert('Text node split: ' + [Link]);" />
<input type="button" value="Delete" onclick="[Link](0, 2);" />
<input type="button" value="Replace" onclick="[Link](0, 4,
'Zap!');" />
</form>

</body>
</html>
- This example allows you to interact with the text node of the paragraph.
- The buttons trigger different modifications to the text node, such as
appending data, inserting it at a specific position, splitting the node, or replacing
part of the text.

The DOM and HTML Elements

- The DOM (Document Object Model) is a representation of HTML documents


in a tree structure where each node corresponds to a part of the document, such
as elements, attributes, and text.
- JavaScript can interact with this tree, allowing you to modify the content,
structure, and style of a webpage dynamically.

- To effectively work with the DOM, it’s important to be familiar with HTML
syntax, as many DOM properties correspond to HTML attributes.

Common HTML Attributes in the DOM

For example, a paragraph element in HTML might look like this:

<p align="left" id="uniqueID" class="className" style="color: blue;"


title="Advisory text" lang="en" dir="ltr">Paragraph content</p>

The DOM provides corresponding properties for these attributes, such as:
- ‘align’ → ‘align’
- ‘id’ → ‘id’
- ‘class’ → ‘className’
- ‘style’ → ‘style’ (more specifically, it's an object in DOM Level 2)
- ‘title’ → ‘title’
- ‘lang’ → ‘lang’
- ‘dir’ → ‘dir’

- For example, the following code accesses the paragraph's ‘id’ in the DOM:
var element = [Link]('uniqueID');
[Link]([Link]); // Outputs: uniqueID

Event Handlers
-- You can also use DOM properties to set event handlers. For instance, in HTML:

<button onclick="alert('Clicked!')">Click Me</button>

In the DOM, you can set this as:


var button = [Link]('buttonID');
[Link] = function() { alert('Clicked!'); };

Special Cases for HTML-to-DOM Mapping


- Some attributes may not map directly to JavaScript due to reserved words or
syntax conflicts. For example:
- The ‘for’ attribute in the ‘<label>‘ tag conflicts with the ‘for’ keyword in
JavaScript, so it's mapped to ‘htmlFor’ in the DOM.

Similarly:
- Attributes like ‘char’ and ‘charoff’ for the ‘<col>‘ tag are mapped to ‘ch’ and
‘choff’.

Working with Tables in the DOM


Tables have more complex structures in HTML. In the DOM, you can interact
with elements like ‘<thead>‘, ‘<tfoot>‘, and ‘<tbody>‘, and modify the rows and cells
dynamically using methods such as ‘createElement’, ‘appendChild’, and
‘removeChild’.

DOM HTML Editor Example

Here’s an example of a simple DOM HTML Editor using JavaScript:


<!DOCTYPE html>
<html>
<head>
<title>DOM HTML Editor 0.1</title>
<script type="text/javascript">
function addElement() {
var choice = [Link];
var theElement =
[Link]([Link][choice].text)
;
var textNode =
[Link]([Link]);
var insertSpot = [Link]('addHere');
[Link](textNode);
[Link](theElement);
}

function deleteNode() {
var deleteSpot = [Link]('addHere');
if ([Link]()) {
var toDelete = [Link];
[Link](toDelete);
}
}

function showHTML() {
alert("Not easily performed without innerHTML");
}
</script>
</head>
<body>
<h1 style="text-align: center;">Simple DOM HTML Editor</h1>
<div id="addHere" style="background-color: #ffffcc; border: solid;"></div>
<br><br>

<form id="htmlForm" name="htmlForm" action="" method="get">


<select id="elementList" name="elementList">
<option>B</option>
<option>BIG</option>
<option>CITE</option>
<option>CODE</option>
<option>EM</option>
<option>H1</option>
<option>H2</option>
<option>H3</option>
<option>H4</option>
<option>H5</option>
<option>H6</option>
<option>P</option>
<option>SAMP</option>
<option>SMALL</option>
<option>STRIKE</option>
<option>STRONG</option>
<option>SUB</option>
<option>SUP</option>
<option>VAR</option>
</select>
<input type="text" value="Default"/>
<input type="button" value="Add Element" onclick="addElement();" />
<br><br>
<input type="button" value="Delete Element" onclick="deleteNode();" />
</form>
</body>
</html>
In this example:
- The user can select an HTML element (e.g., ‘<B>‘, ‘<P>‘, ‘<H1>‘) and add it to a
designated area (‘addHere’).
- The user can delete the last added element with the "Delete Element" button.

Explanation:
1. addElement(): This function creates the selected HTML element (e.g., ‘<B>‘,
‘<P>‘) and adds text to it, then appends it to the ‘addHere’ div.
2. deleteNode(): This function deletes the last child of the ‘addHere’ div.
3. showHTML(): Placeholder for showing the HTML content of the div (but a
simple alert is used here).

Pyq’s Question :
1) Explain DOM and CSS Elements with example.

The DOM and CSS


- Dynamic manipulation of CSS properties via the DOM allows developers to
create interactive and visually dynamic web pages.
- DOM Level 2 supports CSS property changes, and similar capabilities exist in
earlier object models like Microsoft's DHTML.
- Below are the key concepts and examples:

Inline Style Manipulation


- The ‘style’ property of an HTML element in JavaScript enables inline CSS
manipulation.

Example:
<p id="myParagraph">This is a test</p>

‘To dynamically change the text color to green:

let element = [Link]("myParagraph");


[Link] = "green";

CSS Property Name Conversion


- CSS property names often use hyphenated syntax, while DOM properties use
camelCase for JavaScript.

- A CSS property like ‘background-color’ is converted to ‘backgroundColor’ in


JavaScript.
- For reserved words in JavaScript, such as ‘float’, use ‘cssFloat’.

Common CSS Properties and Their JavaScript Equivalents

1. Border-Related Properties:
- ‘border-bottom-style’ → ‘borderBottomStyle’
- ‘border-width’ → ‘borderWidth’

2. Font Properties:
- ‘font-family’ → ‘fontFamily’
- ‘font-size’ → ‘fontSize’
- ‘font-style’ → ‘fontStyle’

3. Margin and Padding:


- ‘margin-top’ → ‘marginTop’
- ‘padding-left’ → ‘paddingLeft’

4. Spacing and Line Properties:


- ‘letter-spacing’ → ‘letterSpacing’
- ‘line-height’ → ‘lineHeight’

5. List Properties:
- ‘list-style’ → ‘listStyle’
- ‘list-style-image’ → ‘listStyleImage’
Dynamic Style Using Classes and Collections

- In the previous section, we focused on manipulating a single tag’s style.


- Now, we will explore dynamic styling using CSS classes and collections of
elements, which allows you to modify multiple elements at once.

Manipulating Class-Based Styles

- CSS classes are commonly used to apply styles to multiple elements. Consider
a simple CSS style sheet with two classes:

<style type="text/css">
.look1 { color: black; background-color: yellow; font-style: normal; }
.look2 { background-color: orange; font-style: italic; }
</style>

And an HTML element with a class:

<p id="myP1" class="look1">This is a test</p>

- You can easily change the class of this element with JavaScript to dynamically
update its appearance:

var theElement = [Link]("myP1");


[Link] = "look2";

- This would change the paragraph's appearance to match the ‘.look2’ class.

Manipulating Styles of Multiple Elements

- If you want to change the style of multiple elements, you can use methods like
‘getElementsByTagName()’ to access all elements of a particular type and then
modify each element's style.

For example, changing the alignment of all paragraphs:

var allParagraphs = [Link]('p');


for (var i = 0; i < [Link]; i++) {
allParagraphs[i].[Link] = 'left';
}

- This loops through all the ‘<p>‘ elements and sets their text alignment to "left".

Accessing and Modifying Complex Style Rules

- The DOM Level 2 provides an interface to interact with stylesheets directly.


- This allows you to access CSS rules found in ‘<style>‘ tags or linked external
stylesheets and modify them dynamically.

To access the first ‘<style>‘ element in a document:

var firstStyleSheet = [Link][0];

You can also access other properties of the stylesheet, such as:

- ‘type’: The MIME type of the style sheet (e.g., ‘text/css’).


- ‘disabled’: A Boolean value indicating if the stylesheet is disabled.
- ‘href’: The link to the external stylesheet (if any).
- ‘title’: The title of the stylesheet.
- ‘media’: The media type for which the stylesheet is designed (e.g., ‘screen’).

Modifying CSS Rules with DOM


To add, remove, or modify rules in a style sheet, you can use methods like
‘insertRule()’ and ‘deleteRule()’ in DOM Level 2:
- insertRule(): Adds a new rule to a stylesheet.

[Link]('p { color: red; }', 0);

This adds a rule that changes the color of all ‘<p>‘ elements to red.

- deleteRule(): Removes a rule from the stylesheet.

[Link](0);

This deletes the first rule from the stylesheet.

Modifying Individual Style Properties


- You can access and modify individual properties in a rule. For example, to
change the color of the first rule in the stylesheet:

[Link][0].[Link] = 'blue';

- This changes the color property of the first CSS rule to blue. For Internet
Explorer, use:

[Link][0].[Link] = 'blue';

The DOM Versus DHTML Object Models

- Some JavaScript developers have avoided the complexity of the DOM Level 1
by relying on older-style collections such as ‘[Link][]’,
‘[Link][]’, and even proprietary collections like ‘[Link][]’.
- While these older methods are not fully standard, they are supported in DOM
Level 0 for compatibility with older browsers.
- Despite the limitations of certain parts of the DOM (such as adding content
dynamically), proprietary features (like ‘innerHTML’ in Internet Explorer) are
sometimes added to other browsers for ease of use.
- This makes DHTML (Dynamic HTML) features popular because they enable
dynamic manipulation of the document with relative ease.

- For example, using ‘innerHTML’ allows you to quickly add or modify HTML
content in a browser:

[Link]("myDiv").innerHTML = "<p>New content</p>";

- This can be convenient for simpler tasks but may not be as flexible as working
directly with the DOM.

The Power of ‘innerHTML’

- The ‘innerHTML’ property is supported by most modern browsers, including


Netscape 6+, Opera 7+, and Internet Explorer 4+.
- This property makes it easy to read and modify the HTML content inside an
element.

Reading HTML Content with ‘innerHTML’


- When you use ‘innerHTML’, it gives you the HTML content of an element as a
string. For example, if you have the following HTML:

<p id="para1">This is a <em>test</em> paragraph.</p>

- You can use JavaScript to retrieve the content like this:

var theElement = [Link]("para1");


alert([Link]);

- This will show the inner HTML content of the ‘<p>‘ element, which includes the
‘<em>‘ tag and the text "test".

Modifying HTML Content with ‘innerHTML’

- You can also use ‘innerHTML’ to change the content of an element. For example,
to change the text inside a ‘<p>‘ tag:

var theElement = [Link]("para1");


[Link] = "I am replacing the text in the p tag.";

- This will update the content of the ‘<p>‘ tag with the new text.

‘innerText’, ‘outerText’, and ‘outerHTML’

- Internet Explorer also supports ‘innerText’, ‘outerText’, and ‘outerHTML’


properties. These work similarly to ‘innerHTML’, but there are key differences:

- ‘innerText’: This is like ‘innerHTML’ but it treats the content as plain text. If
you try to set HTML tags in the text, they will not be rendered as HTML.

[Link] = "<b>test</b>";

- This will show the string ‘<b>test</b>‘ instead of bold text.

- ‘outerText’ and ‘outerHTML’: These properties are similar to ‘innerText’ and


‘innerHTML’, but they also affect the element itself.

- ‘outerHTML’: If you set ‘outerHTML’, the entire element is replaced by the


new HTML.

[Link] = "<b>test</b>";

This will remove the ‘<p>‘ element and replace it with ‘<b>test</b>‘.
‘[Link][]’

- The ‘[Link][]’ collection is a non-standard feature in Internet Explorer,


and it contains all the HTML elements in the document.
- Although the standard DOM does not have this feature, you can simulate it in
browsers that follow the DOM by using ‘getElementsByTagName("*")’.

- For example, here's how you could simulate ‘[Link][]’ using the DOM:

if (![Link]) {
[Link] = [Link]("*");
}

var allTags = "";


for (var i = 0; i < [Link]; i++) {
allTags += [Link][i].tagName + "\n";
}
alert(allTags);

- This code will display all the tags in the document, similar to how ‘[Link][]’
would.

Example Code

<!DOCTYPE html>
<html>
<head>
<title>DOM Test</title>
</head>
<body>
<p id="p1" align="center">A paragraph of <em>text</em> is just an example</p>
<br>
<script type="text/javascript">
if (![Link]) {
[Link] = [Link]("*");
}

var allTags = "";


for (var i = 0; i < [Link]; i++) {
allTags += [Link][i].tagName + "\n";
}

alert(allTags);
</script>
</body>
</html>

Output :

HTML
HEAD
BODY
P
BR
SCRIPT

- This example shows how you can loop through all the tags in the document and
display their names.
Pyq’s question :
1) Differentiate between HTML and DHTML.

HTML vs DHTML

Overview of Events and Event Handling

Expected Question :
1) Explain event and event handler with an example.

- Browsers allow JavaScript to respond to user actions, such as clicking a link,


submitting a form, or hovering over an element.
- These user actions are called events.

Event Model:
- Events are crucial for interactive web pages. When a user interacts with a web
page, an event is triggered, and JavaScript can respond by executing event
handlers.
- The event model defines how events are processed and associated with
elements on the page.

Event Handlers:
- An event handler is JavaScript code that runs in response to a specific event.
- For example, a button click can trigger a pop-up window, or a form field change
can trigger data validation.

Event Object:
- When an event occurs, the browser provides an Event object containing details
about the event, such as the target element (the HTML element where the event
occurred).

Ways to Bind Event Handlers


Event handlers can be bound to elements in several ways:

1. Traditional HTML attributes (e.g., ‘<form onsubmit="myFunction();">‘).


2. Using JavaScript to bind handlers (e.g.,
‘[Link]("myForm").onsubmit = myFunction;’).
3. Proprietary methods like Internet Explorer's ‘attachEvent()’.
4. DOM2 methods like ‘addEventListener()’ to attach event listeners.

Ways Events are Triggered

Events can be triggered in various ways:

1. Implicitly by the browser in response to user actions (e.g., a button click).


2. Explicitly by JavaScript (e.g., using ‘[Link][0].submit()’).
3. Proprietary methods like Internet Explorer's ‘fireEvent()’.
4. Explicitly using DOM2 methods like ‘dispatchEvent()’.
Basic Event Model

- The basic event model is widely supported and simple to understand, with
enough features for most developers.
- It is compatible with both proprietary browser models and the newer DOM2
event model, which offers more flexibility and advanced features for complex
web applications.

Event Binding in (X)HTML


- HTML supports event binding for most elements using attributes like ‘onclick’,
‘onmouseover’, etc.
- These attributes allow JavaScript code to be executed when a specific event
happens on an element.
- As the browser processes the page, it binds the JavaScript to the
corresponding elements.

Example:

<a href="[Link] onclick="alert('Proceeding to


DOM');">Read about the WBC DOM</a>

- In this example, when the link is clicked, an alert box will pop up saying
"Proceeding to DOM."

Event Attributes in (X)HTML

The primary event attributes supported in (X)HTML include:

- ‘onblur’: Triggered when an element loses focus.


- ‘onchange’: Triggered when a form field's value is modified.
- ‘onclick’: Triggered when an element is clicked.
- ‘ondblclick’: Triggered when an element is double-clicked.
- ‘onfocus’: Triggered when an element gains focus.
- ‘onkeydown’: Triggered when a key is pressed down while focused on the
element.
- ‘onkeypress’: Triggered when a key is pressed and released while focused on
the element.
- ‘onkeyup’: Triggered when a key is released while focused on the element.
- ‘onload’: Triggered when an object (e.g., window, image) has finished loading.
- ‘onmousedown’: Triggered when a mouse button is pressed over an element.
- ‘onmousemove’: Triggered when the mouse is moved over an element.
- ‘onmouseout’: Triggered when the mouse moves away from an element.
- ‘onmouseover’: Triggered when the mouse moves over an element.
- ‘onmouseup’: Triggered when the mouse button is released over an element.
- ‘onreset’: Triggered when a form is reset.
- ‘onselect’: Triggered when text is selected by the user.
- ‘onsubmit’: Triggered when a form is about to be submitted.
- ‘onunload’: Triggered when the browser is navigating away from the current
document.

Allowed Elements for Event Binding in (X)HTML


You can bind events to many common elements in (X)HTML, such as:

- Common Elements: ‘<a>‘, ‘<button>‘, ‘<input>‘, ‘<select>‘, ‘<textarea>‘, ‘<form>‘,


‘<img>‘, ‘<span>‘, ‘<table>‘, ‘<div>‘, and others.
- Browser-Specific Elements: In Internet Explorer 4+ and Netscape 4+,
additional elements like ‘<frameset>‘, ‘<ilayer>‘, ‘<layer>‘, ‘<font>‘, and ‘<applet>‘ can
also trigger events.

Non-standard Event Binding in (X)HTML

- Some browsers, particularly Internet Explorer, support non-standard methods


to bind events.
- One such approach involves using a ‘<script>‘ tag with a ‘for’ attribute to specify
the ‘id’ of the element and an ‘event’ attribute to specify the handler.

For example:

<p id="myParagraph">Mouse over this text!</p>


<script type="text/jscript" for="myParagraph" event="onmouseover">
alert("Non-standard markup is a burden for developers and users alike!");
</script>

- This method is not part of the official HTML or XHTML specifications.


- Its support is limited to Internet Explorer, and it may not work in other
browsers. Due to this incompatibility, developers are advised to avoid using this
syntax.

Binding Event Handler Attributes with JavaScript

- Instead of using HTML event attributes directly, JavaScript provides a more


flexible and maintainable approach.
- This method separates the structure of the document from its behavior,
making it easier to manage and update.

Example 1: Binding a Click Handler to a Button

<form action="#" method="get" name="myForm" id="myForm">


<input name="myButton" id="myButton" type="button" value="Click me"/>
</form>
<script type="text/javascript">
[Link] = new Function("alert('Thanks for
clicking!')");
</script>

- In this example, the click handler for the button is set using JavaScript.
- When the button is clicked, it shows an alert message: "Thanks for clicking!"
Example 2: Binding a Mouseover Handler to a Button

<script type="text/javascript">
function showMessage() {
alert("Ouch! Get off me!");
}
</script>
<form action="#" method="get" name="myForm" id="myForm">
<button id="myButton">Mouse over me!</button>
</form>
<script type="text/javascript">
[Link]("myButton").onmouseover = showMessage;
</script>

- Here, the ‘mouseover’ event for the button is bound to the ‘showMessage’
function.
- When the mouse moves over the button, it triggers the alert: "Ouch! Get off
me!"

Important Considerations

1. Ensure DOM Availability: JavaScript code that binds event handlers should
be executed only after the document elements are fully loaded into the DOM.
If an event handler is set before the element is available, a runtime error will
occur.

2. Solutions to Avoid Errors:


- Set the event handler after the document’s ‘onload’ event.
- Alternatively, place the script tag that assigns the event handler after the
element in the HTML document.
Netscape 4 Event Model

Pyq’s question ;
1) Describe Netscape 4 Event Model in detail.

- Netscape 4 introduced the first event model with advanced features that were
not present in the basic event model.
- This model provided greater flexibility in handling events, especially with
respect to where and how events could be handled within the document object
hierarchy.
- However, this model is considered obsolete and is only found in Netscape 4
browsers.
- Since Mozilla-based browsers adopted the DOM2 model and Netscape 6+ was
based on Mozilla, this model is now considered an evolutionary dead end.

Event Object in Netscape 4

- When an event occurs in Netscape 4, the browser creates an ‘Event’ object and
passes it to the handler.
- This event object contains several useful properties that help developers
handle events more efficiently.

Properties of the Event Object

1. data: An array of strings containing the URLs of objects that were dragged
and dropped.

2. modifiers: A bitmask indicating which modifier keys (like ALT, CONTROL,


META, and SHIFT) were pressed during the event. The bitmask is a combination
of constants:
- ‘ALT_MASK’
- ‘CONTROL_MASK’
- ‘META_MASK’
- ‘SHIFT_MASK’

3. pageX: The horizontal coordinate where the event occurred (relative to the
page).

4. pageY: The vertical coordinate where the event occurred (relative to the
page).

5. screenX: The horizontal coordinate where the event occurred (relative to the
entire screen).

6. screenY: The vertical coordinate where the event occurred (relative to the
entire screen).

7. target: A reference to the object on which the event occurred (e.g., the
element that was clicked).

8. type: A string indicating the event type (e.g., "click").

9. which: For mouse events, this property indicates which mouse button was used
(1 for left, 2 for middle, 3 for right). For keyboard events, it provides the
numeric (Unicode) value of the key pressed.

Handling the Event Object in Event Handlers

- In Netscape 4, the way the ‘Event’ object is passed to the handler is important.
- When the handler is defined as an (X)HTML attribute (like ‘onclick’), the ‘Event’
object is implicitly available within the text of the handler through the ‘event’
identifier.

- For example, in the following code, the x-coordinate of the click is shown using
the ‘screenX’ property of the event:
<a href="[Link]" onclick="alert('Click at ' + [Link]);">Click me!</a>

- However, this ‘event’ object is only accessible within the event handler's
attribute text.
- If you try to use it outside of the event handler's scope (such as in a
JavaScript function), it will not be available, and an error will occur. This is a
common mistake.

-For example, the following code will throw an error because ‘event’ is not
defined in the ‘myHandler’ function:

<script type="text/javascript">
function myHandler() {
alert("Event type: " + [Link]); // Error: event is not defined
}
</script>
<a href="#" onclick="myHandler(); return false;">Click me!</a>

Fixing the Issue by Passing the Event Object


- To fix the issue, you should explicitly pass the ‘Event’ object to the handler
function.

- Here's the correct way to handle it:

<script type="text/javascript">
function myHandler(event) {
alert("Event type: " + [Link]); // Works fine now
}
</script>
<a href="#" onclick="myHandler(event); return false;">Click me!</a>
- In this corrected version, the ‘event’ object is passed manually to the
‘myHandler’ function, making the event data accessible within the function and
avoiding the error.

Internet Explorer 4+ Event Model


- The event model in Internet Explorer (IE) 4 and later is more advanced
compared to Netscape 4.
- In IE4 and later, every element on the page is represented as an object. This
enables a more robust and flexible set of elements capable of generating events.
- Additionally, Microsoft has implemented a broader variety of events for each
object.
- However, there is a significant downside: the event propagation order in
Internet Explorer is opposite to that of Netscape 4, which complicates cross-
browser programming, especially when backwards compatibility is required.

Attaching Event Handlers in Internet Explorer


- In Internet Explorer, you can attach event handlers to elements either by
using traditional (X)HTML attributes or with JavaScript, as with other
browsers.
- However, Internet Explorer also provides an additional method for attaching
event handlers:
- the ‘attachEvent()’ method. This method was introduced in Internet Explorer
5, likely in anticipation of the DOM2 standard and to support DHTML behaviors.

Syntax of ‘attachEvent()’
- The ‘attachEvent()’ method allows you to attach an event handler to an object.
The syntax is:

[Link]("event to handle", eventHandler);

Where:
- The first parameter is a string that specifies the event type (e.g., "onclick").
- The second parameter is the function that should be invoked when the event
occurs.

The return value of ‘attachEvent()’ is a Boolean indicating whether the


attachment of the event handler was successful.

Removing Event Handlers in Internet Explorer


- To remove an event handler that was attached using ‘attachEvent()’, you use
the ‘detachEvent()’ method. The syntax is:

[Link]("event to handle", eventHandler);

- You need to pass the exact same arguments (event type and event handler)
that were used when attaching the event.

Example: Using ‘attachEvent()’ to Attach and Detach Events

<!DOCTYPE html>
<html>
<head>
<title>IE Attach/Detach Event Test</title>
<script type="text/javascript">
// Function to show an alert when event occurs
function showAuthor() {
alert("Oscar Wilde");
}

// Function to enable the event (attach the event handler)


function enableEvent() {
[Link]("onmouseover", showAuthor);
}
// Function to disable the event (detach the event handler)
function disableEvent() {
[Link]("onmouseover", showAuthor);
}
</script>
</head>
<body onload="enableEvent();">
<em id="someText">We may be in the gutter, but some of us are looking at the
stars</em>
<form action="#" method="get">
<input type="button" value="Attach Event" onclick="enableEvent();"/>
<input type="button" value="Detach Event" onclick="disableEvent();"/>
</form>
</body>
</html>

- In the example, the ‘onmouseover’ event is attached to the ‘someText’ element


when the page loads.
- When the user hovers over the text, the ‘showAuthor()’ function is triggered,
displaying an alert with the text "Oscar Wilde".
- There are two buttons in the form that allow the user to attach or detach the
event handler dynamically.

Event Object in Internet Explorer

- When an event occurs in Internet Explorer, the browser creates a transient


‘Event’ object and makes it available to the appropriate handler.
- Unlike Netscape 4, where the event object needs to be explicitly passed to
the handler, in Internet Explorer the event object is automatically available as
a global variable named ‘event’.

Properties of the Event Object in Internet Explorer


- srcElement: Reference to the object for which the event is intended. This is
essentially the target element of the event.
- type: A string that represents the event type, such as "click".
- clientX: Numeric value indicating the horizontal coordinate of the event within
the client area.
- clientY: Numeric value indicating the vertical coordinate of the event within
the client area.
- screenX: Numeric value indicating the horizontal coordinate of the event
relative to the entire screen.
- screenY: Numeric value indicating the vertical coordinate of the event relative
to the entire screen.
- button: Numeric value indicating the mouse button pressed. The primary button
is represented by 0, though this value may vary across different systems.
- keyCode: Numeric value representing the Unicode value of the key pressed (for
keyboard events).
- altKey: A Boolean indicating whether the ALT key was pressed.
- ctrlKey: A Boolean indicating whether the CTRL key was pressed.
- shiftKey: A Boolean indicating whether the SHIFT key was pressed.
- cancelBubble: A Boolean indicating whether the event should stop bubbling up
the event hierarchy.
- returnValue: A Boolean indicating the return value of the event handler. Other
handlers in the bubbling chain may modify this value unless event bubbling has
been canceled.
- fromElement: Reference to the element that the mouse is moving away from
in ‘mouseover’ or ‘mouseout’ events.
- toElement: Reference to the element that the mouse is moving to in ‘mouseover’
or ‘mouseout’ events.
DOM2 Event Model

Pyq’s question :
1) Explain DOM2 Event Model.

- The DOM2 Event Model describes a standardized method to handle events


within a hierarchical structure like an (X)HTML document.
- It defines how events are created, captured, processed, and canceled, along
with the event propagation behavior, which details how an event travels from its
source to the target and what happens afterward.
- This model incorporates the basic event model while introducing concepts from
proprietary models like those of Netscape 4 and Internet Explorer.

Event Propagation
In the DOM2 model, events propagate through two main phases:

1. Capture Phase: The event starts from the top (Document) and travels down
through the object hierarchy toward the target. This phase mimics the behavior
found in Netscape 4.

2. Bubbling Phase: After reaching the target element, the event bubbles back
up the hierarchy to the top. This phase is similar to the event model used in
Internet Explorer 4+.

During both phases, events can be intercepted, handled, or redirected by any


object along the way.

Browser Support
- Mozilla-based browsers (e.g., Mozilla, Firefox, Netscape 6+) were the first to
adopt the DOM2 Event Model.
- Opera 7 and Safari (on macOS) also offer strong support for the DOM2 model.
- Internet Explorer, starting from version 6, does not fully support DOM2
events, creating potential compatibility issues for developers working with
multiple browsers.

Binding Event Handlers to Objects

- Event handlers can be attached to elements using either (X)HTML attributes


or JavaScript.
- However, for browsers that support DOM2, it's recommended to use
JavaScript because the event object cannot be accessed through the event
handler attributes as easily.

Example of Binding Using JavaScript:

<p id="myElement">Click on me</p>


<p>Not on me</p>
<script type="text/javascript">
function handleClick(e) {
alert("Got a click: " + e);
}
[Link]("myElement").onclick = handleClick;
</script>

DOM2 Event Binding Methods


- The DOM2 introduces the ‘addEventListener()’ method to provide more control
over event handling. Here are the main advantages of using this method:

1. Multiple Handlers: You can bind several handlers to the same event on an
element. Each handler will be executed when the event occurs, but the order of
execution is arbitrary.

2. Capture Phase Handling: It allows you to handle events during the capture
phase, unlike event handler attributes (e.g., ‘onclick’) that only trigger during the
bubbling phase.
3. Binding to Text Nodes: Prior to DOM2, it wasn’t possible to bind events to
text nodes, but now it is.

#Syntax of ‘addEventListener()’:
[Link]("event", handler, capturePhase);

Where:
- ‘object’: The DOM node to which the event listener is attached.
- ‘"event"‘: A string representing the event type (e.g., "click", "mouseover").
- ‘handler’: The function that will be executed when the event occurs.
- ‘capturePhase’: A Boolean (‘true’ for capture phase, ‘false’ for bubbling phase).

#Example: Using ‘addEventListener()’ for Capture and Bubble Phases

- Capture Phase Example:


To register a function ‘changeColor()’ for the capture phase of a "mouseover"
event:
[Link]('myText').addEventListener("mouseover",
changeColor, true);

- Bubbling Phase Example:


To add a "mouseover" event handler for the bubbling phase:
[Link]('myText').addEventListener("mouseover",
swapImage, false);

Removing Event Handlers


- Event handlers can be removed using ‘removeEventListener()’. You must use the
same arguments that were used when the event was added.

Example: Removing an Event Handler:

To remove the first handler from the previous example while keeping the
second:
[Link]('myText').removeEventListener("mouseover",
changeColor, true);

Event Objects
- Browsers that support the DOM2 Event Model pass an Event object to event
handlers.
- This object contains additional information about the event that occurred.
- It is similar to the event objects used in proprietary event models, like those
of Netscape and Internet Explorer.
- The properties of the Event object can vary based on the type of event, but
there are some common read-only properties across all event objects.

Common Event Object Properties:

1. bubbles
- A boolean indicating whether the event bubbles up through the DOM
hierarchy.

2. cancelable
- A boolean indicating whether the event can be canceled.

3. eventPhase
- A numeric value indicating the current phase of event flow.
- 1: Capture phase
- 2: Target phase
- 3: Bubble phase

4. type
- A string that specifies the type of the event (e.g., "click", "keydown").

5. target
- The node to which the event was originally dispatched (i.e., the target of the
event).
6. currentTarget
- The node whose handler is currently executing (i.e., the node the handler is
bound to).

DOM2 Browser Events


- Different types of events have specific bubbles and cancelable behaviors.
Below is a table that outlines some common browser and mouse events:

DOM2 Mouse Events


DOM2 Keyboard Events

Summary of Major Features of the Event Models

Binding a Handler:
- In the Basic model (Netscape 4), handlers are bound using (X)HTML
attributes.
- In Internet Explorer 4+, handlers can be bound through (X)HTML attributes
or the ‘attachEvent()’ method.
- In the DOM2 model, handlers are bound via (X)HTML attributes or the
‘addEventListener()’ method.

Detaching a Handler:
- In the Basic model (Netscape 4), handlers are detached by setting the
(X)HTML attribute to null via script.
- In Internet Explorer 4+, handlers can be detached using ‘detachEvent()’.
- In the DOM2 model, handlers can be detached using ‘removeEventListener()’.

The Event Object:


- In the Basic model (Netscape 4), there is no Event object.
- In Internet Explorer 4+, the Event object is available globally as
‘[Link]’.
- In the DOM2 model, the Event object is passed as an argument to the event
handler.

Canceling the Default Action:


- In the Basic model (Netscape 4) and Internet Explorer 4+, the default action
is canceled by returning false.
- In the DOM2 model, the default action can be canceled by calling
‘preventDefault()’.

Event Propagation:
- In the Basic model (Netscape 4), events propagate from the Window down to
the target.
- In Internet Explorer 4+, events propagate from the target up to the
Document.
- In the DOM2 model, events propagate from the Document down to the target
and then back up to the Document.

Stopping Propagation:
- In the Basic and Internet Explorer 4+ models, there is no direct way to stop
propagation.
- In the DOM2 model, propagation can be stopped using the ‘stopPropagation()’
method.

Redirecting an Event:
- In the Basic model (Netscape 4) and Internet Explorer 4+, events cannot be
redirected.
- In the DOM2 model, events can be redirected using the ‘dispatchEvent()’
method.

Event Model Issues

Choosing the Event Model:


- The choice of event model depends on the browsers used by your audience.
- Internet Explorer's event model is likely to remain the most widely used for
the next few years.

Decline of Netscape 4:
- The Netscape 4 event model is quickly fading as more browsers adopt the
Mozilla-based browsers and the DOM2 standard.
- Although the DOM2 model is available in many modern browsers, Internet
Explorer's model is still prevalent.

Cross-Browser Compatibility:
- Writing cross-browser event handlers is essential for modern web
development.
- For standard events and simple tasks, writing your own handlers can work.
- For complex tasks, developers may need to rely on or create cross-browser
event libraries.
Some pyq’s important program

Q. Write a JavaScript program to create a Home page of any website and change
background color using.
On mouse over event (mouse over)
On focus event (focus)

JavaScript program to create a Home page of any website and change


background color using On mouse over event (mouse over) and On focus event
(focus)

- In this program, we create a simple homepage for a website that uses


JavaScript to change the background color based on the ‘onmouseover’ and
‘onfocus’ events.

- These events allow users to interact with the webpage in a dynamic way, making
the interface more engaging.

Key Concepts Used:

1. ‘onmouseover’ Event:
Triggered when the mouse pointer is moved over an HTML element.
Example: Change the background color of the webpage when the user hovers
over a button.

2. ‘onfocus’ Event:
Triggered when an input field gets focused (clicked or tabbed into).
Example: Change the background color of the input field when the user clicks
on it.
Program Code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home Page Example</title>
<style>
/* Styling for the body */
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 0;
padding: 0;
}

/* Styling for the header */


h1 {
color: #333;
}

/* Styling for the button */


button {
background-color: lightblue;
border: none;
padding: 10px 20px;
font-size: 18px;
cursor: pointer;
margin: 20px;
border-radius: 8px;
}
button:hover {
background-color: lightgreen;
}

/* Styling for the input field */


input {
padding: 10px;
border: 2px solid #ccc;
font-size: 16px;
margin: 10px;
border-radius: 8px;
}
input:focus {
border-color: #6666ff;
background-color: #e6e6ff;
}
</style>
</head>
<body>
<!-- Page Content -->
<h1>Welcome to My Website</h1>
<p>Hover over the button or focus on the input field to see the color
changes.</p>

<!-- Button with onmouseover event -->


<button onmouseover="changeBackgroundColor('lightyellow')">
Hover over me!
</button>

<!-- Input field with onfocus event -->


<br>
<input type="text" placeholder="Click or focus here"
onfocus="changeBackgroundColor('lightpink')">
<!-- JavaScript Code -->
<script>
// Function to change background color
function changeBackgroundColor(color) {
[Link] = color;
}
</script>
</body>
</html>

Explanation of Code:

1. HTML Structure:
- ‘<h1>‘: Displays the heading of the webpage ("Welcome to My Website").
- Button: A button is added with an ‘onmouseover’ event to change the
background color when the mouse hovers over it.
- Input Field: An input field is added with an ‘onfocus’ event to change the
background color when clicked or tabbed into.

2. CSS Styling:
- Adds styles for the webpage, button, and input field for better presentation.
- Includes hover (‘:hover’) and focus (‘:focus’) pseudo-classes to change button
and input field styles directly.

3. JavaScript Function:
- ‘changeBackgroundColor(color)’: A reusable function to change the
background color of the webpage dynamically.
- The function is triggered on the ‘onmouseover’ and ‘onfocus’ events of the
button and input field, respectively.
Expected Output:

1. Initial State:
- The homepage displays a title, a button, and an input field.
- The background color is white by default.

2. On Mouse Hover (Button):


- When the user hovers over the button, the background color of the webpage
changes to lightyellow.

3. On Input Focus:
- When the user clicks or tabs into the input field, the background color of
the webpage changes to lightpink.
Unit-6 Using JavaScripts

Some important Question :


-> Explain Various methods to control windows and list out window features.
-> Explain the form handling and the terms form fields, validations, Dynamic
forms, Form usability with an example.
-> Design and implement a simple calculator using Java script for operations
like addition, multiplication, subtraction, division, square of a number.
-> List and explain various popular windows events?
-> What is frame and explain the HTML tags to create frames and how to
change the properties of the frame.
-> Create a student information Form to accept information like Name,
Address, City, State, Gender, Mobile Number and email id. Perform
validations for:
• Correct Names
• Mobile Names
• Email I.D.’s
-> Describe with example the methods alert() and confirm() of Window
object.
-> Explain Common Window Properties Related to Frames.
-> Write a short note on Form Usability and Java Script.
-> Explain Label, Fieldset, and Legend as other form elements.
-> What is a significance of form validation?
-> State and explain Window features.
Introduction to Window
- JavaScript's Window object represents the browser window or frame where
a document is displayed.
- It provides various properties and methods that control the appearance and
behavior of the browser window, including its size, position, and chrome (such as
buttons and scrollbars).
- The Window object is the top object in the JavaScript object hierarchy,
meaning it contains references to nearly all other objects within the browser.

Dialogs :
Pyq’s question :
1) Describe with example the methods alert() and confirm() of Window
object.

A dialog box is a small window in the GUI that appears to request some action
from the user. JavaScript supports three types of dialogs:

1. Alert Dialog
- The ‘alert()’ method of the Window object creates a small window with a
message and an OK button.
- It is used to display simple notifications or debugging messages.
- The alert dialog is modal, meaning the user must dismiss it before interacting
with the rest of the page.

- Syntax:
alert(string);

- Example:
javascript
alert("Hello, World!");
- Note: The message in the alert window can be a string, variable, or the result
of an expression. If a different data type is passed, it will be coerced into a
string.

- Use Case: The alert dialog is typically used for debugging purposes, where
developers want to quickly display messages to users.

2. Confirm Dialog
- The ‘confirm()’ method creates a window with a message and two buttons: OK
and Cancel. The user clicks either to confirm or cancel an action.
- This method is often used to ask the user for confirmation before proceeding
with an operation.

- Syntax:
confirm(string);

- Example:
let isConfirmed = confirm("Do you want to submit the form?");

- Return Value: The ‘confirm()’ method returns a Boolean value:


- ‘true’ if the OK button is clicked.
- ‘false’ if the Cancel button is clicked or the dialog is closed.

- Note: In JavaScript, the button labels for the confirm dialog cannot be
customized. It's common to use Yes/No buttons for better usability instead of
OK/Cancel, but the basic method does not support this customization.

3. Prompt Dialog
- The ‘prompt()’ method creates a dialog box that allows the user to enter a
value.
- It is typically used to collect short pieces of data from the user, such as a
name or email address. The dialog includes a text field where the user can type
input.
- Syntax:
var result = prompt(promptString, defaultValueString);

- Example:
let userName = prompt("Please enter your name:", "John Doe");

- Return Value: The ‘prompt()’ method returns the value entered by the user as
a string. If the user cancels the prompt or closes the dialog, it returns ‘null’.

- Note: If only one argument is passed, the second argument is undefined, but
it is advisable to pass an empty string ‘""‘ as a default value if you do not want
the prompt to have a value by default.

- These dialog boxes are useful for gathering simple inputs or providing
messages to users in a web application.
- However, they may disrupt the user experience if overused, as they block
interaction with the rest of the page.

Opening and Closing Generic Windows


- JavaScript provides the open() and close() methods to manage generic windows
that are used to display webpages or results.
- These methods allow developers to create new windows or close existing ones
based on user actions.

Opening a Window
- The ‘open()’ method is used to open a new browser window with a specified URL,
name, and features.
- You can also set attributes like the window’s size, whether it can be resized,
and whether it has scrollbars.

Syntax:
[Link](url, name, features, replace);
- url: The URL of the document to load into the new window.
- name: The name of the window (used when referencing the window in the
‘target’ attribute of HTML links).
- features: A comma-delimited string that specifies the attributes of the new
window (such as ‘width’, ‘height’, ‘scrollbars’, etc.).
- replace: An optional Boolean value. If ‘true’, the URL will replace the contents
of the current window.

Example:

<a href="#" onclick="javascript: secondwindow = open('[Link]


'yahoo', 'height=300, width=200, scrollbars=yes');">
Open Window
</a>

- In this example, clicking the link opens a new window with the Yahoo website
loaded inside it.
- The window has a height of 300 pixels, a width of 200 pixels, and scrollbars
enabled.

Closing a Window
- Once a window is opened using ‘open()’, you can close it using the ‘close()’
method.

Syntax:
[Link]();

- windowName: The reference to the window object you want to close. This is
usually the variable you assigned when you opened the window (e.g.,
‘secondwindow’).

Example:
<input type="button" value="Close Window" onclick="[Link]();"/>
- In this example, when the button is clicked, the ‘[Link]()’ method
will be called to close the window.

Error Handling When Closing a Window


- If you try to close a window that doesn't exist, JavaScript will throw an error.
- However, if the window was created at least once, it will not throw an error
even if the window is no longer open, as the object still exists in the scope chain.

- To safely close a window, you can check if the window object exists before
attempting to close it.

Example:
if (secondwindow) {
[Link]();
}

- This ensures that the ‘close()’ method is called only if the window object is
defined.

Window Features

Pyq’s question :
1) State and explain Window features.

- When opening a new window using JavaScript's ‘[Link]()’ method, the


‘features’ parameter allows you to customize the window's behavior and
appearance.
- Here are some of the available features you can specify:

Common Window Features


- alwaysLowered:
‘yes/no’
Determines if the window should always stay beneath other windows. It may
pose a security risk.

- alwaysRaised:
‘yes/no’
Makes the window always stay on top of other windows.

- dependent:
‘yes/no’
Makes the window dependent on its parent. If the parent window is closed, the
dependent window also closes.

- directories:
‘yes/no’
Controls whether the directories button in the browser's window is shown.

- fullscreen:
‘yes/no’
Makes the window take over the entire screen (only in Internet Explorer).

- height:
Pixel value
Sets the height of the entire window, including the chrome (the window border
and title bar).

- hotkeys:
‘yes/no’
Disables all hotkeys except the essential ones, like quitting, for the new
window.

- innerHeight:
Pixel value
Sets the height of the inner part of the window where the document is
displayed.

- innerWidth:
Pixel value
Sets the width of the inner part of the window where the document is
displayed.

- left:
Pixel value
Specifies the horizontal position of the window from the left side of the
screen.

- location:
‘yes/no’
Controls whether the location bar (URL) is displayed in the window.

- menubar:
‘yes/no’
Specifies whether the browser's menu bar should be shown.

- outerHeight:
Pixel value
Sets the height of the outer part of the window, including the chrome.

- outerWidth:
Pixel value
Sets the width of the outer part of the window, including the chrome.

- resizable:
‘yes/no’
Indicates whether the window can be resized.
- screenx:
Pixel value
Specifies the horizontal distance from the screen's origin to where the window
should open (specific to some browsers like Netscape).

- screeny:
Pixel value
Specifies the vertical distance from the screen's origin for the window's
position.

- scrollbars:
‘yes/no’
Determines if the window should have scrollbars.

- status:
‘yes/no’
Specifies if the status bar at the bottom of the window should be visible.

- titlebar:
‘yes/no’
Specifies if the title bar of the window should be visible.

- toolbar:
‘yes/no’
Specifies if the toolbar should be visible in the new window.

- top:
Pixel value
Specifies the vertical position of the window from the top of the screen
(specific to IE, use ‘screeny’ for cross-browser compatibility).

- width:
Pixel value
Sets the width of the window. It is better to use ‘innerWidth’ for the content
width.

- z-lock:
‘yes/no’
Prevents the window from changing its stacking order relative to other
windows, even if it gains focus.

Example:

javascript
var windowOptions = "directories=no, location=no, width=300, height=300";
var mywindow = open("[Link] "mywindow", windowOptions);

In this example, a new window is opened with the Yahoo website, with specific
options: no directories or location bar, and a window size of 300x300 pixels.

Writing to Windows
- Once a new window is opened, you can use JavaScript to dynamically write
content to it or manipulate its DOM.
- You can use the ‘[Link]()’ or ‘[Link]()’ methods to write
HTML directly into the newly created window.
- The ‘[Link]()’ method is called after writing to finalize the content,
and ‘[Link]()’ brings the window into focus.

Example 1: Writing to a Window

var mywindow = open('', 'mywin', 'height=300, width=300');


[Link]('Hi there. ');
[Link]('This is my new window');
[Link]();
[Link]();
- In this example, we open a new window, write two lines of text into it, and then
focus on the window.

Example 2: Writing HTML Content to a Window

[Link]("<html><head><title>fun</title></head><body>");
[Link]("<h1>Hi from JavaScript</h1></body></html>");

- This writes a full HTML document to the newly opened window, including a title
and a header.

Example 3: Custom Alert with Dynamic Content

<!DOCTYPE html>
<html>
<head>
<title>JavaScript 1.1</title>
<script type="text/javascript">
function customAlert(title, message){
if (jsWindow != null){
jsWindow = [Link]("", "", "width=300, height=200");
var windowHTML = "<html><head><title>" + title + "</title></head>";
windowHTML += "<body bgcolor='black' text='yellow'><h1 align='center'>";
windowHTML += message + "</h1><hr /><div align='center'>";
windowHTML += "<form><input type='button' value='CLOSE'
onclick='[Link]()'>";
windowHTML += "</form></div></body></html>";
[Link](windowHTML);
[Link]();
}
}

function askJS(){
var question = prompt("What is your question?", "");
if (question != null) {
if (question == "")
customAlert("Angry", "You insult me!");
else
customAlert("Bored", "Don't waste my time.");
}
}
</script>
</head>
<body>
<div align="center">
<h1>JavaScript 1.1</h1>
<hr>
<form action="#" method="get">
<input type="button" value="Ask the JS" onclick="askJS();"/>
</form>
</div>
</body>
</html>

- In this example, the ‘askJS()’ function prompts the user for input.
- Based on the input, a custom alert with dynamic content is created and
displayed in a new window.
- If the user doesn't provide any input, a different message is shown.

Controlling Windows (Methods)

Pyq’s question :
1) Explain Various methods to control windows and list out window
features.
- JavaScript provides several methods to manipulate windows.
- These methods allow you to control window behavior such as focusing, moving,
resizing, scrolling, and changing the window's location.

Focusing and Blurring Windows

1. ‘[Link]()’:
- This method brings a window into focus, making it the active window that the
user can interact with.
- Example: If a window has been opened, you can call this method to bring it
to the front.

2. ‘[Link]()’:
- This method removes focus from the current window, which means the
window will no longer be the active one.
- Example: If you want to shift the focus from a window to another, you would
use ‘[Link]()’.

Moving Windows :

1. ‘[Link](horizontalpixels, verticalpixels)’:
- This method moves the window by a specified number of pixels relative to
its current position.
- Parameters:
- ‘horizontalpixels’: The number of pixels to move the window horizontally
(positive to move right, negative to move left).
- ‘verticalpixels’: The number of pixels to move the window vertically (positive
to move down, negative to move up).
- Example:
javascript
[Link](100, 100);

This moves the window 100 pixels to the right and 100 pixels down.
2. ‘[Link](x-coord, y-coord)’:
- This method moves the window to a specific location on the screen using
exact coordinates.
- Parameters:
- ‘x-coord’: The horizontal coordinate on the screen.
- ‘y-coord’: The vertical coordinate on the screen.
- Example:
javascript
[Link](1, 1);

This moves the window to the top-left corner of the screen (coordinates 1,1).

Resizing Windows

1. ‘[Link](horizontal, vertical)’:
- This method resizes the window by a specified number of pixels in both the
horizontal and vertical directions.
- Parameters:
- ‘horizontal’: The number of pixels to increase or decrease the width of the
window (positive values increase, negative values decrease).
- ‘vertical’: The number of pixels to increase or decrease the height of the
window (positive values increase, negative values decrease).
- Example:
javascript
[Link](10, 10);

This makes the window 10 pixels wider and 10 pixels taller.

2. ‘[Link](width, height)’:
- This method resizes the window to a specified width and height.
- Parameters:
- ‘width’: The width to set for the window in pixels.
- ‘height’: The height to set for the window in pixels.
- Example:
[Link](100, 100);

This resizes the window to be exactly 100x100 pixels.

Scrolling Windows

1. ‘[Link](horizontalpixels, verticalpixels)’:
- This method scrolls the window by a specified number of pixels horizontally
and vertically.
- Parameters:
- ‘horizontalpixels’: The number of pixels to scroll horizontally (positive to
scroll right, negative to scroll left).
- ‘verticalpixels’: The number of pixels to scroll vertically (positive to scroll
down, negative to scroll up).
- Example:
javascript
[Link](10, 0);

This scrolls the window 10 pixels to the right.

2. ‘[Link](x-coord, y-coord)’:
- This method scrolls the window to a specific location, specified by pixel
coordinates.
- Parameters:
- ‘x-coord’: The horizontal pixel position to scroll to.
- ‘y-coord’: The vertical pixel position to scroll to.
- Example:
javascript
[Link](100, 100);

This scrolls the window to position 100 pixels to the right and 100 pixels
down.
3. ‘[Link]()’:
- This is an older method that is similar to ‘scrollBy()’. It is not commonly used
today but still exists for backward compatibility.

Setting Window Location

1. Using the ‘Location’ Object:


- The ‘Location’ object is part of the ‘Window’ object and provides information
about the current URL of the window. It also allows you to modify the window's
URL.
- You can set the window's location by assigning a new URL to ‘[Link]’.

Example of setting the location:

<form action="#" method="get">


<input type="button" value="Go to Yahoo"
onclick="[Link]='[Link] />
</form>

This example demonstrates how to use a button to navigate to a new webpage


(Yahoo).

2. Accessing Location Parts:


- You can also access different parts of the URL using the ‘Location’ object.
For instance, you can get the hostname or the protocol.
- Example:
javascript
alert([Link]); // Displays the current hostname (e.g.,
[Link])
alert([Link]); // Displays the protocol (e.g., http:, https:)

By utilizing these methods, you can dynamically control the window’s behavior,
appearance, and location from within JavaScript.
Accessing a Window's History
- JavaScript allows you to interact with a browser's history using the ‘History’
object.
- This object provides methods and properties to navigate through the history
list and manipulate the browser's history.

1. Navigating History:
- The Back and Forward buttons in the browser navigate through the history
list. Similarly, you can use JavaScript to move forward and backward in the
browser's history.
- Example:

<a href="javascript: [Link]();">Forward</a>


<a href="javascript: [Link]();">Back</a>

2. Accessing Specific History Entries:


- The ‘[Link]()’ method allows you to move to a specific entry in the history
list relative to the current position. You can pass a negative value to go backward
and a positive value to go forward in the history.
- Example:

<a href="javascript: [Link](-2);">Back two times</a>


<a href="javascript: [Link](3);">Forward three times</a>

3. Checking the Length of the History List:


- The ‘[Link]’ property returns the number of entries in the history
list. You can use this to navigate to the last item in the history list.
- Example:

<a href="javascript: [Link]([Link]-1);">Last


Item</a>
Controlling the Window's Status Bar
- The status bar is the small text area typically at the bottom of the browser
window, displaying status messages like download progress, page loading
information, etc. JavaScript provides a way to modify this status bar.

1. Using the ‘status’ and ‘defaultStatus’ Properties:


- ‘[Link]’: Displays a transient message for a short period.
- ‘[Link]’: Displays a default message that remains until
changed.
- Example: Change the status message when hovering over a link:

<a href="[Link] onmouseover="[Link]='Don\'t Leave


Me!'; return true;" onmouseout="[Link]=''; return true;">
Go to Yahoo!
</a>

2. Setting Default Status:


- To set a default message for the status bar, you can assign a string to the
‘defaultStatus’ property.
- Example:

<script type="text/javascript">
defaultStatus = 'JavaScript is fun!';
</script>

Setting Window Timeouts and Intervals

- JavaScript allows you to execute functions after a specified amount of time


using the ‘setTimeout()’ and ‘setInterval()’ methods.

1. ‘setTimeout()’:
- This method triggers a function or statement after a specified number of
milliseconds.
- Syntax:
timerId = setTimeout(functionToExecute, timeInMilliseconds);

- Example:
<script type="text/javascript">
var timer = setTimeout(function() { alert("Time's up!"); }, 5000); // 5
seconds
</script>
- To cancel the timeout, you use ‘clearTimeout(timerId)’.

2. ‘setInterval()’:
- This method triggers a function at regular intervals, specified in milliseconds.
- Syntax:
timerId = setInterval(functionToExecute, intervalTimeInMilliseconds);

- Example:

<script type="text/javascript">
var timer = setInterval(function() { alert('Are we there yet?'); }, 2000); //
Every 2 seconds
</script>

Window Events

- The ‘Window’ object also supports several events that can be used to respond
to changes in the window's state, such as losing or gaining focus, loading or
unloading the document, and resizing the window.

- Some common events include:


1. ‘onblur’:
- Fired when the window loses focus (e.g., when the user switches to another
window).
2. ‘onerror’:
- Fired when a JavaScript error occurs.

3. ‘onfocus’:
- Fired when the window gains focus (e.g., when the user returns to the
window).

4. ‘onload’:
- Fired when the document is completely loaded into the window.

5. ‘onresize’:
- Fired when the window is resized.

6. ‘onunload’:
- Fired when the document is unloaded, such as when navigating away from the
current page or closing the window.

These events can be used to handle specific behaviors, such as loading content,
handling errors, or responding to user actions.

Example:

<script type="text/javascript">
[Link] = function() {
alert('The window has been resized!');
};
</script>

- These methods and events provide powerful control over the window and its
behavior, allowing you to create interactive and dynamic web applications.
Extended Window Events
- There are several additional events related to the ‘Window’ object that provide
more control over the window’s behavior.
- These include events that trigger just before or after certain actions occur,
such as printing or unloading the window.

1. ‘onbeforeunload’:
- Triggered just before the window is unloaded, allowing you to display a
confirmation message to the user before they leave the page.

2. ‘onafterprint’:
- Triggered after the window has been printed.

3. ‘onbeforeprint’:
- Fires just before the window is printed or shown in print preview.

4. ‘onhelp’:
- Fires when the Help key (usually F1) is pressed.

5. ‘onresizeend’:
- Triggered when the window resizing has finished (i.e., the user stops dragging
the window’s corner).

6. ‘ondragdrop’:
- Triggered when a document is dragged onto the window (supported by
Netscape only).

7. ‘onresizestart’:
- Fires when the user starts resizing the window (i.e., when dragging the
window's corner begins).

8. ‘onscroll’:
- Triggered whenever the window is scrolled in any direction.
Example:

<body onload="alert('Entering window');" onunload="alert('Leaving window');">

- In this example, the ‘onload’ event is triggered when the page loads, and the
‘onunload’ event is triggered when the page is being unloaded.

Frames: A Special Case of Windows

Pyq’s question :
b) What is frame and explain the HTML tags to create frames and how to
change the properties of the frame.

- Frames often confuse developers because they are technically separate


windows within the browser window.
- A frame can be manipulated as a window object, and JavaScript provides
specific methods for working with frames.

1. Manipulating Frames:
- Each frame in the browser window is accessible through ‘[Link][]’.
This array contains references to each individual frame object in the window.

2. Useful Properties for Frames:


- ‘frames[]’: Array of all frame objects in the current window.
- ‘[Link]’: The number of frames in the current window.
- ‘frames[name]’: A reference to a frame by its name.
- ‘parent’: A reference to the parent window of the frame.
- ‘self’: A reference to the current window (or frame).
- ‘top’: A reference to the top-most window (in a multi-level frame structure).
Example of a frameset with multiple frames:

<!DOCTYPE html>
<html>
<head>
<title>FrameSet Test</title>
</head>
<frameset rows="33%, *, 33%">
<frame src="[Link]" name="frame1" id="frame1" />
<frame src="[Link]" name="frame2" id="frame2" />
<frame src="[Link]" name="frame3" id="frame3" />
</frameset>
</html>

3. Accessing Frames:
- To determine the number of frames in a window:
javascript
[Link]
[Link]
[Link]
[Link]

- To access a specific frame:


javascript
[Link][0].name
[Link]["frame1"]

Inline Frames
- Inline frames (or ‘<iframe>‘) are used to embed another document within a page.
Unlike framesets, inline frames are directly embedded within the document.

1. Creating an Inline Frame:


- You can add an inline frame using the ‘<iframe>‘ tag. This allows you to load
external content within your web page.

Example:

<!DOCTYPE html>
<html>
<head>
<title>Iframe Example</title>
</head>
<body>
<h1>Regular Content here</h1>
<iframe src="[Link] name="ifr1" id="ifr1" height="200"
width="200"></iframe>
<h1>More content here</h1>
</body>
</html>

2. Accessing Inline Frames:


- If the inline frame has a name or ID, you can use JavaScript to interact with
it. For example, use ‘getElementById()’ to access the frame.

Applied Frames :
Loading Frames with Links
- You can load content into frames using links, either by specifying the ‘target’
attribute in HTML or by using JavaScript.

1. Using the ‘target’ Attribute:


- The ‘target’ attribute is used to specify the name of the frame where the
linked content should be loaded.
Example:
<a href="[Link] target="framename">Google</a>

2. Using JavaScript to Target Multiple Frames:


- You can also use JavaScript to load content into multiple frames at once.

Example:
<a href="javascript:[Link]['frame1'].location='[Link]
[Link]['frame2'].location='[Link]
Two sites
</a>

- This method allows you to control the content in multiple frames with a single
action, providing a way to update several parts of a page simultaneously.

Frame Bursting
- Frame busting is a technique used to prevent clickjacking, which occurs when
a malicious website loads a page from another domain into a frame and overlays
it with a counterfeit page.
- This allows the attacker to trick users into interacting with hidden parts of
the original page (like buttons or links) that lead to unintended actions.

How Frame Bursting Works:

- The goal of frame bursting is to ensure that a page is not loaded inside a frame
from another website.
- JavaScript Code for Frame Busting:
function frameBuster() {
if (window != top) {
[Link] = [Link]; // Forces the page to break out of the
frame
}
}
[Link] = frameBuster;

- Explanation: This code checks if the current window is the top-level window
(not inside a frame). If it's inside a frame, it redirects the top window to the
current page’s URL, effectively breaking out of the frame.

Frame Building

- On the other hand, frame building addresses the opposite problem, where a
page might get opened outside of its original frameset.
- For example, users might bookmark a frame within a frameset or launch a link
from a frameset into a new window.
- To avoid this issue, we need to ensure that the document is always viewed
within the context of its original frameset.

Rebuilding the Frameset :


- To ensure the document is loaded correctly within the frameset, we can use
JavaScript to check if the current window is inside a frameset and, if not,
dynamically rebuild the frameset.

JavaScript Code for Frame Building:

if ([Link] == location) {
[Link] = '[Link]'; // Redirects to frameset page if not
in frameset
}

- Explanation: This code checks if the current window is the top window
(‘[Link] == location’).
- If not, it redirects to the frameset page, ensuring the document stays within
the intended frame context.
Form Handling :

Pyqs question :
1) Explain the form handling and the terms form fields, validations,
Dynamic.

- One of the most common uses of JavaScript is for form validation, which allows
you to check the contents of a form before sending it to the server.
- This is crucial for ensuring the data is correct and complete, improving user
experience, and reducing server load.

Benefits of JavaScript Form Validation:


- Reduce round trips to the server: Validating forms client-side reduces the
number of requests sent to the server for invalid data.
- Improve usability: Immediate feedback is provided to the user, guiding them
to fix errors before submission.
- Rectify form data: JavaScript can automatically fix common input mistakes,
reducing user frustration.
- Reduce server load: By ensuring the data is correct client-side, the number of
invalid submissions sent to the server is minimized.

Form Basics:
- Forms in HTML are accessed through the ‘Form’ object in JavaScript, which is
a part of the ‘Document’ object model (DOM).

Form Tag Structure:

<form id="formID" name="formName" action="submitURL" method="POST">


<!-- form fields -->
</form>

Form Properties and Methods:


- ‘action’: The URL to which the form data will be submitted.
- ‘method’: The method to submit form data (GET or POST).
- ‘enctype’: Defines how the form data should be encoded when submitting to
the server (e.g., ‘application/x-www-form-urlencoded’ or ‘multipart/form-data’).
- ‘target’: Specifies where to display the response (e.g., in a new window or within
a frame).

- In JavaScript, you can access form elements and validate them before
submission, ensuring that the data is correct and formatted properly before
sending it to the server.

Form Methods:

1. ‘reset()’ method: Clears all form fields (like ‘<input type="reset" />‘).
2. ‘submit()’ method: Submits the form (like ‘<input type="submit" />‘).
3. Event Handlers: ‘onreset’ and ‘onsubmit’ can be used to trigger events when a
form is reset or submitted.

Accessing Forms
Forms can be accessed in several ways:

1. By Number: Access through ‘[Link][]’ (accesses the form by its


index in the document).
2. By Name: Access via ‘[Link]['formName']’ or ‘[Link]’.
3. By ID: Access using ‘[Link]()’.

Example:

<form name="customerform" id="customerform" action="#" method="get">


<input type="text" name="firstname" id="firstname" />
<!-- other fields -->
</form>
Access the form via:
- ‘[Link][0]’ (first form on the page).
- ‘[Link]['customerform']’ or ‘[Link]’
(using form name).

Accessing Form Fields :


Form fields can be accessed using the ‘elements[]’ collection.

Example:
- To refer to the first field in the form:
[Link][0]

- To refer to a specific field by name:


[Link]

You can also iterate through the form fields:


for (let i = 0; i < [Link]; i++) {
// Do something with each form element
}

Form Elements
HTML supports various form elements including:

- Text Fields: ‘<input type="text">‘, ‘<textarea>‘.


- Password Fields: ‘<input type="password">‘.
- Checkboxes and Radio Buttons: ‘<input type="checkbox">‘, ‘<input type="radio">‘.
- Hidden Fields: ‘<input type="hidden">‘.
- File Uploads: ‘<input type="file">‘.

Buttons :
There are several types of buttons:

1. Submit: ‘<input type="submit" />‘ — Submits the form data.


2. Reset: ‘<input type="reset" />‘ — Resets form fields to their initial state.
3. Generic Button: ‘<input type="button" value="Click Me" />‘ — Triggers an action
using an event handler like ‘onclick’.

- The submit and reset buttons have default actions, while a generic button
requires a custom event handler.

Text Fields :

1. Single-line Text Fields:


<input type="text" />

2. Password Fields:
<input type="password" />

3. Multi-line Text Area:


<textarea name="name" id="idname" cols="30" rows="4">Default
text</textarea>

Checkboxes and Radio Buttons


Both use the ‘<input>‘ tag but differ in behavior:

1. Checkbox:
<input type="checkbox" name="male" id="male" value="male" />

2. Radio Button:
<input type="radio" name="yes" id="yes" value="yes" />

- Both elements allow the user to select options, with checkboxes allowing
multiple selections and radio buttons allowing only one selection within a group.

Hidden Fields
- Hidden fields are used to store state information without rendering on the
page. They are sent along with the form data when submitted.

Syntax:
<input type="hidden" name="user_id" value="12345" />

File Upload Fields


- The file upload field allows users to upload files. It can specify allowed file
types using the ‘accept’ attribute.

Syntax:
<input type="file" id="fileupload" name="file" accept="image/png, image/jpeg" />

- The ‘accept’ attribute defines the types of files the user can upload (e.g.,
‘image/png’, ‘application/pdf’).

Select Menus :
- In HTML, the ‘<select>‘ tag is used to create pull-down menus, which can either
allow single or multiple choices.

Single-choice Menu (Pull-down Menu)


This allows the user to select only one option from a list.

Example:
<strong>Single Robot Choice:</strong>
<select name="robot" id="robot">
<option>Friend</option>
<option>Cook</option>
<option>Security</option>
<option>Trainer</option>
</select>
Multiple-choice Menu (Scrolled List)
This allows the user to select more than one option from the list. It is created
by adding the ‘multiple’ attribute.

Example:
<strong>Multiple Robot Choice:</strong>
<select name="robotMulti" id="robotMulti" size="4" multiple="multiple">
<option>Security</option>
<option>Trainer</option>
<option>Friend</option>
<option>Cook</option>
</select>

Option Elements :

The ‘<option>‘ elements define the choices in a ‘<select>‘ menu. Each ‘<option>‘ can
have different properties:

- ‘defaultSelected’: A Boolean indicating if the option is selected by default.


- ‘index’: The index (position) of the option in the options collection of the
‘<select>‘ element.
- ‘selected’: A Boolean indicating if the option is currently selected.
- ‘Text’: The text between the ‘<option>‘ tags, which is displayed to the user.
- ‘value’: The value attribute that is sent to the server when the form is
submitted.

Option Groups :
- You can group related options within a ‘<select>‘ menu using the ‘<optgroup>‘ tag.
This allows for better organization and visual separation of choices.

Example:
<select name="robotchooser" id="robotchooser">
<option>Choose your robot</option>
<option>----</option>
<option>Butler</option>
<optgroup label="Security Models">
<option>Man</option>
<option>K-9</option>
</optgroup>
<option>Female</option>
<optgroup label="Friend Models">
<option>Male</option>
</optgroup>
<option>Trainer</option>
</select>

Output:
- Choose your robot
- Butler
- Security Models
- Man
- K-9
- Female
- Friend Models
- Male
- Trainer

The ‘<optgroup>‘ tag creates labeled groups within the dropdown, helping
organize the options.

Other Form Elements: Label, Fieldset, and Legend

- HTML provides additional elements to enhance form accessibility and


structure.
Label
- The ‘<label>‘ tag is used to associate a label with a form field. This improves
usability, especially for non-visual user agents (screen readers).

Example:
<label>Username:
<input type="text" id="username" name="username" />
</label>

<label for="userpassword">Password:</label>
<input type="password" id="userpassword" name="userpassword" />

The ‘for’ attribute in ‘<label>‘ is used to link the label to a specific input element
by matching the input's ‘id’.

Fieldset and Legend


- The ‘<fieldset>‘ tag groups related elements inside a form, providing a box
around them. The ‘<legend>‘ tag gives a title to the grouped elements, improving
clarity.

Example:

<form action="#" method="get">


<fieldset>
<legend>Login Info</legend>
<label>Username:
<input type="text" id="username" name="username" />
</label>
<br/>
<label for="userpassword">Password:</label>
<input type="password" id="userpassword" name="userpassword" />
</fieldset>
</form>
Form Validation
- Form validation ensures that the user provides valid and complete input before
submission.
- It helps avoid unnecessary server requests and improves user experience.

Validation Process
- Before they happen: Prevent errors before the user enters data.
- As they happen: Check and display errors as users fill in the form.
- After they happen: Check form data before submission.

- Typically, form validation is done just before submission, where if any errors
are found, they are displayed, and the form submission is canceled by returning
‘false’ in the event handler.

Abstracting Form Validation


- To avoid repeating validation logic, you can create reusable validation functions
that can be applied to any form.

Example of a basic email validation function:


function isEmail(field) {
var s = [Link];
if (isEmpty(s)) {
alert("Email may not be empty");
[Link]();
return false;
}
if (/[^@]+@[^@]+/.test(s)) {
return true;
}
alert("E-mail not in valid form!");
[Link]();
return false;
}
Drop-in Form Validation
- You can create a reusable set of validation functions and apply them
dynamically to form fields by passing their names and the type of validation
required. Here's an example:

var validations = [
["[Link]", "notblank"],
["[Link]", "validemail"],
["[Link]", "isnumber"]
];

for (i = 0; i < [Link]; i++) {


var field = eval(validations[i][0]);
var checkToMake = validations[i][1];

switch (checkToMake) {
case 'notblank':
if (isEmpty([Link])) {
alert("Field may not be empty");
[Link]();
return false;
break;
case 'validemail':
if (!looksLikeEmail(field)) return false;
break;
case 'isnumber':
if (!isInteger(field)) return false;
break;
}
return true;
}

function isInteger(field) {
// logic for checking integer
}

function looksLikeEmail(field) {
// logic for checking email format
}

function isEmpty(s) {
return !s || [Link]() === "";
}

- In this way, you can easily validate different forms with different field
requirements by adjusting the validation array.
- This modular approach improves maintainability and reusability.

Dynamic Forms Example

- A dynamic form can be used to calculate values like subtotals, tax, shipping
cost, and grand total as the user interacts with the form.
- The form shown here calculates the total costs based on quantities of items
entered by the user.
- JavaScript is used to perform calculations and update fields in real time.

HTML and JavaScript Code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"[Link]
<html>
<head>
<title>Dynamic Form Demo</title>
<script type="text/javascript">
<!--
// Declare constants for item prices and tax rate
var widgetCost = 1.50; // Price of one widget
var gadgetCost = 2.70; // Price of one gadget
var thingieCost = 1.25; // Price of one thingie
var taxRate = 0.075; // Tax rate (7.5%)
var shippingCost = 0; // Shipping cost (calculated dynamically)

// Function to check if input is a number


function isNumberInput(field, event) {
var key, keyChar;

// Event handling for different browsers


if ([Link]) {
key = [Link]; // For Internet Explorer
} else if (event) {
key = [Link]; // For other browsers
} else {
return true;
}

// Check if the key pressed is a number


if (key == null || key == 0 || key == 13 || key == 27) {
return true; // Allow certain keys (null, 0, Enter, Escape)
}

// Get the character corresponding to the keycode


keyChar = [Link](key);

// Allow only digits


if (/\d/.test(keyChar)) {
[Link] = "";
return true;
} else {
[Link] = "Field Numbers only.";
return false; // Reject non-numeric input
}
}

// Function to format the calculated value to two decimal places


function format(value) {
var temp = [Link](value * 100);
return temp / 100; // Round the value to two decimal places
}

// Main calculation function that updates the form fields


function calc() {
with ([Link]) {
// Calculate totals for widgets, gadgets, and thingies
[Link] = format([Link] * widgetCost);
[Link] = format([Link] * gadgetCost);
[Link] = format([Link] * thingieCost);

// Calculate subtotal by adding the totals of all items


[Link] = format(
parseFloat([Link]) +
parseFloat([Link]) +
parseFloat([Link])
);

// Calculate tax based on the subtotal


[Link] = format([Link] * taxRate);

// Determine shipping cost based on the selected option


for (i = 0; i < [Link]; i++) {
if (shipping[i].checked) {
shippingCost = parseFloat(shipping[i].value);
}
}

// Calculate grand total (subtotal + tax + shipping cost)


[Link] = format(
parseFloat([Link]) +
parseFloat([Link]) +
shippingCost
);
}
}
<!--
</script>
</head>

<body>
<!-- Form structure -->
<form id="myform" name="myform" action="#" method="get">
<!-- Input fields for item quantities and their total costs -->
Widgets:
<input type="text" name="widgets" id="widgets" size="2" value="0"
onchange="calc();" onkeypress="return isNumberInput(this, event);" />
@1.50 each
<input type="text" id="widgettotal" name="widgettotal" size="5"
readonly="readonly" />
<br />

Gadgets:
<input type="text" name="gadgets" id="gadgets" size="2" value="0"
onchange="calc();" onkeypress="return isNumberInput(this, event);" />
@2.70 each
<input type="text" id="gadgettotal" name="gadgettotal" size="5"
readonly="readonly" />
<br />
Thingies:
<input type="text" name="thingies" id="thingies" size="2" value="0"
onchange="calc();" onkeypress="return isNumberInput(this, event);" />
@1.25 each
<input type="text" id="thingietotal" name="thingietotal" size="5"
readonly="readonly" />
<br /><br /><br />

<!-- Subtotal, tax, and shipping options -->


<em>Subtotal:</em>
<input type="text" id="subtotal" name="subtotal" size="8" value="0"
readonly="readonly" />
<br /><br /><br />

<em>Shipping:</em>
Next day:
<input type="radio" value="12.00" name="shipping" id="shipping"
checked="true" onclick="calc();" />
2-day:
<input type="radio" value="7.00" name="shipping" id="shipping"
onclick="calc();" />
Standard:
<input type="radio" value="3.00" name="shipping" id="shipping"
onclick="calc();" />
<br /><br /><br />

<strong>Grand Total:</strong>
<input type="text" id="grandtotal" name="grandtotal" size="8"
readonly="readonly" />
</form>
</body>
</html>
Detailed Explanation of the Code

1. Form Structure:
- The form contains input fields for entering quantities of "widgets,"
"gadgets," and "thingies," and displays their total costs.
- The user can select a shipping option (Next day, 2-day, or Standard), and
the corresponding shipping cost is applied.

2. JavaScript Functions:
- ‘isNumberInput’: Ensures that only numeric values are entered in the
quantity fields. It blocks any non-numeric characters.
- ‘format’: Rounds the calculated values to two decimal places to represent
money values correctly.
- ‘calc’: This is the main function that performs the calculations:
- It calculates the total cost for each item (widget, gadget, thingie) by
multiplying the quantity by the item cost.
- It calculates the subtotal by summing the individual totals.
- It applies tax by multiplying the subtotal by the tax rate.
- It determines the shipping cost based on the selected shipping option.
- It calculates the grand total by adding the subtotal, tax, and shipping
cost.

3. Event Handling:
- ‘onchange’: Each input field triggers the ‘calc’ function when the value is
changed, updating the totals dynamically.
- ‘onkeypress’: This event restricts input to numeric characters only, ensuring
no invalid characters are entered.

4. Dynamic Calculation:
- As the user updates the quantities or selects different shipping options, the
form automatically recalculates the total values (subtotal, tax, shipping, grand
total) without needing to reload the page.
Key Points to Remember:

- Real-Time Calculation: The form dynamically updates the displayed totals as


the user changes input values.
- User Input Validation: The ‘isNumberInput’ function prevents the entry of non-
numeric values in quantity fields.
- Accurate Currency Representation: The ‘format’ function ensures that the
calculated totals are displayed with two decimal places, simulating real-world
pricing.
Some pyq’s program

Q. Create a student information Form to accept information like Name,


Address, City, State, Gender, Mobile Number and email id. Perform
validations for:
• Correct Names
• Mobile Names
• Email I.D.’s

Create a student information Form to accept information like Name,Address,


City, State, Gender, Mobile Number and email id. Perform
validations for:
• Correct Names
• Mobile Names
• Email I.D.’s

Student Information Form with Validations

- In this program, we create a Student Information Form using HTML and


JavaScript.
- The form collects basic student details like Name, Address, City, State,
Gender, Mobile Number, and Email ID.
- JavaScript validations ensure the correctness of the entered data.

Key Features:

1. Form Inputs:
- Name, Address, City, State, Gender, Mobile Number, and Email ID fields are
created.
2. Validation Rules:
- Name Validation: Only letters are allowed.
- Mobile Number Validation: Must contain exactly 10 digits.
- Email Validation: Checks for a valid email format (e.g., user@[Link]).

3. Error Messages:
- Displays alerts for invalid input values.

Program Code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Information Form</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
padding: 0;
}

h1 {
text-align: center;
color: #333;
}

form {
width: 50%;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 10px;
box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.1);
}

label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}

input, select {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 5px;
}

.gender {
width: auto;
margin-right: 10px;
}

button {
background-color: #007BFF;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}

.error {
color: red;
font-size: 14px;
}
</style>
</head>
<body>
<h1>Student Information Form</h1>

<form id="studentForm" onsubmit="return validateForm()">


<label for="name">Name:</label>
<input type="text" id="name" placeholder="Enter your name">

<label for="address">Address:</label>
<input type="text" id="address" placeholder="Enter your address">

<label for="city">City:</label>
<input type="text" id="city" placeholder="Enter your city">

<label for="state">State:</label>
<input type="text" id="state" placeholder="Enter your state">

<label>Gender:</label>
<input type="radio" id="male" name="gender" value="Male" class="gender">
Male
<input type="radio" id="female" name="gender" value="Female"
class="gender"> Female

<label for="mobile">Mobile Number:</label>


<input type="text" id="mobile" placeholder="Enter your mobile number">

<label for="email">Email ID:</label>


<input type="email" id="email" placeholder="Enter your email address">

<button type="submit">Submit</button>
</form>

<script>
// Function to validate form inputs
function validateForm() {
// Get form inputs
const name = [Link]("name").[Link]();
const mobile = [Link]("mobile").[Link]();
const email = [Link]("email").[Link]();

// Name validation: only letters


const nameRegex = /^[A-Za-z\s]+$/;
if (![Link](name)) {
alert("Name must contain only letters.");
return false;
}

// Mobile number validation: exactly 10 digits


const mobileRegex = /^\d{10}$/;
if (![Link](mobile)) {
alert("Mobile number must contain exactly 10 digits.");
return false;
}

// Email validation: correct format


const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (![Link](email)) {
alert("Please enter a valid email address.");
return false;
}

alert("Form submitted successfully!");


return true;
}
</script>
</body>
</html>

Explanation of Code:

1. HTML Form:
- Includes input fields for Name, Address, City, State, Gender, Mobile
Number, and Email ID.
- Uses ‘<form>‘ to wrap the inputs and specify the onsubmit attribute for
validation.

2. CSS Styling:
- Provides a visually appealing layout with labels, input fields, and a submit
button.
- Input fields and button styles are customized for better readability and user
interaction.

3. JavaScript Validation:
- Validates each input using regular expressions.
- Name Validation: Ensures only letters are allowed.
- Mobile Validation: Checks for a 10-digit number.
- Email Validation: Verifies the format of the email address.
- Displays alerts for incorrect inputs to guide the user.
Expected Output:

1. Initial View:
- A form with fields for Name, Address, City, State, Gender, Mobile Number,
and Email ID appears.

2. Validations:
- Entering invalid inputs (e.g., numbers in the name, less than 10 digits for
mobile, or an incorrect email format) triggers appropriate error messages.

3. Successful Submission:
- Displays "Form submitted successfully!" if all inputs are valid.

Design and implement a simple calculator using Java script for operations like
addition, multiplication, subtraction, division, square of a number.

Design and Implementation of a Simple Calculator Using JavaScript

Objective:
To create a simple calculator that performs the following operations:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Square of a Number

Program Overview:
1. User Interface:
The calculator has buttons for numbers (0-9) and operations (+, -, ×, ÷, and
square).
2. Functionalities:
- Takes two input values for operations like addition, subtraction,
multiplication, and division.
- Calculates the square of a number when the "Square" button is pressed.

3. Output Display:
Displays the result dynamically on the screen.

Program Code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Calculator</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 0;
padding: 0;
}

h1 {
margin-top: 20px;
color: #333;
}

.calculator {
width: 300px;
margin: 50px auto;
padding: 20px;
border: 2px solid #ccc;
border-radius: 10px;
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
}

input[type="number"], .result {
width: 90%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
}

button {
padding: 10px 20px;
margin: 5px;
border: none;
background-color: #007BFF;
color: white;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
}

button:hover {
background-color: #0056b3;
}
</style>
</head>
<body>
<h1>Simple Calculator</h1>
<div class="calculator">
<input type="number" id="num1" placeholder="Enter first number">
<input type="number" id="num2" placeholder="Enter second number">
<div class="result" id="result">Result: </div>

<button onclick="performOperation('add')">Add</button>
<button onclick="performOperation('subtract')">Subtract</button>
<button onclick="performOperation('multiply')">Multiply</button>
<button onclick="performOperation('divide')">Divide</button>
<button onclick="performSquare()">Square</button>
</div>

<script>
function performOperation(operation) {
// Get input values
const num1 = parseFloat([Link]("num1").value);
const num2 = parseFloat([Link]("num2").value);
let result;

// Perform operation based on user selection


if (operation === "add") {
result = num1 + num2;
} else if (operation === "subtract") {
result = num1 - num2;
} else if (operation === "multiply") {
result = num1 * num2;
} else if (operation === "divide") {
if (num2 !== 0) {
result = num1 / num2;
} else {
alert("Division by zero is not allowed!");
return;
}
}

// Display the result


[Link]("result").innerText = ‘Result: ${result}’;
}

function performSquare() {
// Get the first input value
const num1 = parseFloat([Link]("num1").value);

// Calculate the square


const result = num1 * num1;

// Display the result


[Link]("result").innerText = ‘Result (Square): ${result}’;
}
</script>
</body>
</html>

Explanation of Code:

HTML:
- Input Fields:
Two fields (‘id="num1"‘ and ‘id="num2"‘) allow users to enter numbers.
- Buttons:
Buttons trigger different operations (addition, subtraction, multiplication,
division, and square).

CSS:
- Calculator Styling:
The calculator is styled for a clean and user-friendly interface with proper
alignment and colors.

JavaScript:
1. ‘performOperation(operation)’ Function:
- Handles addition, subtraction, multiplication, and division based on the input
parameter (‘operation’).
- Validates inputs and prevents division by zero.
2. ‘performSquare()’ Function:
- Calculates the square of the first input value (‘num1’).

Output:

Initial View:
- Displays input fields for two numbers and buttons for operations.

Operations:
1. Addition: Outputs the sum of two numbers.
2. Subtraction: Outputs the difference of two numbers.
3. Multiplication: Outputs the product of two numbers.
4. Division: Outputs the quotient of two numbers (displays an error for division
by zero).
5. Square: Outputs the square of the first input value.

Result Display:
Results are shown dynamically in the "Result" section.
All The Best !!!

You might also like