0% found this document useful (0 votes)
33 views26 pages

3BSC Web Unit3 - 052433

Web technology notes

Uploaded by

Rakshitha K U
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)
33 views26 pages

3BSC Web Unit3 - 052433

Web technology notes

Uploaded by

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

3BSC WEB TECHNOLOGIES UNT3 NEP

UNIT 3
Two Mark Questions

1. How do static web pages differ from interactive multimedia experiences?

Static web pages:


- Content is fixed and does not change unless the HTML file itself is edited and re-uploaded.
- No interaction or real-time feedback for the user.
- Typically simpler to design and load quickly.

Interactive multimedia experiences:


- Content can change dynamically based on user interactions or other triggers.
- Often includes rich media elements such as video, audio, animations, and interactive forms.
- Provides a more engaging and responsive experience for the user.

2. What is Dynamic HTML?

Dynamic HTML (DHTML) is an umbrella term for a collection of technologies used together to
create interactive and animated web sites. It includes a combination of HTML, CSS, and JavaScript
to enable web pages to change and update in response to user actions without requiring a reload of
the entire page.

3. List out any 2 features of JavaScript.

- Interactivity: JavaScript can respond to user actions, such as mouse clicks, form submissions, and
keyboard events, making web pages interactive.
- DOM Manipulation: JavaScript can access and modify the Document Object Model (DOM) of a
webpage, allowing dynamic changes to the content, structure, and style of the page.

4. What is JavaScript? Write the advantages of JavaScript.

JavaScript is a high-level, interpreted programming language primarily used to create dynamic and
interactive effects within web browsers.

Advantages of JavaScript:
- Client-Side Execution: JavaScript runs in the user’s browser, reducing server load and improving
user experience.
- Ease of Learning and Use: It has a straightforward syntax and is relatively easy for beginners to
learn.
- Versatility: JavaScript can be used for both front-end and back-end development (e.g., using
Node.js).
- Rich Interfaces: JavaScript allows the creation of rich interfaces with drag-and-drop features,
sliders, and other interactive components.

JAYANTI SHANKAR 1
3BSC WEB TECHNOLOGIES UNT3 NEP
5. What are the key similarities between JavaScript and C?

- Syntax: Both languages use a similar C-style syntax, including the use of semicolons to terminate
statements and curly braces for code blocks.
- Control Structures: Both languages support similar control structures, such as if-else statements,
loops (for, while), and switch cases.

6. What do you mean by scripting language? Give one example.

A scripting language is a programming language designed for integrating and communicating with
other programming languages. It is often used for automating processes that would otherwise be
performed step-by-step by a human operator.

Example: JavaScript.

7. What are the different types of comments supported in JavaScript?

- Single-line comments: Start with `//`.


// This is a single-line comment

- Multi-line comments: Enclosed in `/* ... */`.


/* This is a
multi-line comment */

8. How are variables declared and assigned values in JavaScript?

Variables in JavaScript can be declared using `var`, `let`, or `const`.

- Declaration and assignment:


var x = 5; // Using var
let y = 10; // Using let
const z = 15; // Using const

- Re-assignment:
x = 20; // Re-assigning value to x
y = 25; // Re-assigning value to y
// z = 30; // Error: Assignment to constant variable

9. What are some common data types used in JavaScript?

- Number: Represents both integer and floating-point numbers.


- String: Represents a sequence of characters.
- Boolean: Represents true or false values.
- Object: Represents a collection of properties.
JAYANTI SHANKAR 2
3BSC WEB TECHNOLOGIES UNT3 NEP
- Array: Represents an ordered list of values.
- Undefined: Represents a variable that has been declared but not assigned a value.
- Null: Represents the intentional absence of any object value.

10. What is a JavaScript statement? Give an example.


A JavaScript statement is a command that performs an action. Statements are executed in sequence
by the JavaScript engine. Each statement ends with a semicolon (`;`), though this is often optional.

Example:
javascript
let a = 10; // Variable declaration and assignment
console.log(a); // Output the value of 'a' to the console

11. What is the syntax for creating a for loop in JavaScript?


The syntax for a `for` loop in JavaScript is:
for (initialization; condition; increment) {
// code block to be executed
}

Example:
for (let i = 0; i < 5; i++) {
console.log(i);
}

12. What is the purpose of the `eval()` function in JavaScript?


The `eval()` function in JavaScript evaluates a string as a JavaScript expression and executes it.
This function can execute code represented as a string.
let x = 10;
let y = 20;
let result = eval('x + y'); // result will be 30

13. What is the purpose of the `prompt()` function in JavaScript?


The `prompt()` function in JavaScript displays a dialog box that prompts the user for input. It
returns the input value as a string.
let userInput = prompt("Please enter your name:");
console.log("Hello, " + userInput);

14. List any 4 operators used in JavaScript.


- Addition operator (`+`): Adds two values.
let sum = 10 + 20; // 30

- Equality operator (`==`): Compares two values for equality.


let isEqual = (10 == "10"); // true

JAYANTI SHANKAR 3
3BSC WEB TECHNOLOGIES UNT3 NEP
- Logical AND operator (`&&`): Returns true if both operands are true.
let result = (true && false); // false

- Increment operator (`++`): Increments a variable by 1.


let count = 1;
count++; // count is now 2

15. What is the use of `typeof` operator in JavaScript? Give Example.


The `typeof` operator in JavaScript is used to determine the type of a variable or expression. It
returns a string indicating the type.
let number = 42;
console.log(typeof number); // "number"
let text = "Hello";
console.log(typeof text); // "string"

16. What is an array in JavaScript, and how is it defined?


An array in JavaScript is a data structure that can hold multiple values at once, each identified by
an index.
Example of defining an array:
let fruits = ["Apple", "Banana", "Cherry"];

17. Mention the basic operations that are performed on arrays.


- Adding elements: Using `push()`, `unshift()`.
- Removing elements: Using `pop()`, `shift()`, `splice()`.
- Accessing elements: Using index notation.
- Iterating through elements: Using loops (`for`, `forEach`).

18. What is the procedure for removing elements from an array?


- Using `pop()`: Removes the last element from an array.
let fruits = ["Apple", "Banana", "Cherry"];
fruits.pop(); // "Cherry" is removed
- Using `shift()`: Removes the first element from an array.
let fruits = ["Apple", "Banana", "Cherry"];
fruits.shift(); // "Apple" is removed

19. What is DOM?


The Document Object Model (DOM) is a programming interface for web documents. It represents
the page so that programs can change the document structure, style, and content. The DOM
represents the document as a tree of nodes.

20. What is the use of Object-based array functions in JavaScript?


Object-based array functions in JavaScript are methods that operate on arrays as objects, allowing
for manipulation and traversal of array elements. These methods provide powerful and flexible ways

JAYANTI SHANKAR 4
3BSC WEB TECHNOLOGIES UNT3 NEP
to handle arrays, including adding, removing, and transforming elements. Examples include `map()`,
`filter()`, `reduce()`, `forEach()`, and `sort()`.

21. What is the difference between the `push()` and `unshift()` array functions in JavaScript?
- `push()`: Adds one or more elements to the end of an array and returns the new length of the
array.
let arr = [1, 2, 3];
arr.push(4); // arr is now [1, 2, 3, 4]
- `unshift()`: Adds one or more elements to the beginning of an array and returns the new length of
the array.
let arr = [1, 2, 3];
arr.unshift(0); // arr is now [0, 1, 2, 3]

22. What is the purpose of the `splice()` function in JavaScript arrays?


The `splice()` function in JavaScript is used to add or remove elements from an array. It can
remove elements from a specified index and/or insert new elements at that index.
let fruits = ["Apple", "Banana", "Cherry"];
// Remove 1 element at index 1 and add "Blueberry"
fruits.splice(1, 1, "Blueberry"); // ["Apple", "Blueberry", "Cherry"]

23. Define a JavaScript function.


A JavaScript function is a block of code designed to perform a particular task. It is executed when
it is called or invoked.
function greet(name) {
return "Hello, " + name;
}

24. How does parameter passing work?


In JavaScript, parameters are passed to functions by value. This means that the function gets a
copy of the original value. For objects and arrays, the reference to the object or array is passed,
meaning that changes to the object or array within the function will affect the original.
function modifyArray(arr) {
arr.push(4);
}
let numbers = [1, 2, 3];
modifyArray(numbers); // numbers is now [1, 2, 3, 4]

25. Describe the syntax for defining functions in JavaScript.


Functions in JavaScript can be defined using the function declaration or function expression
syntax.
- Function declaration:
javascript
function functionName(parameters) {
// code to be executed
}

JAYANTI SHANKAR 5
3BSC WEB TECHNOLOGIES UNT3 NEP

- Function expression:
const functionName = function(parameters) {
// code to be executed
};

26. Why do some functions return values to the calling statement?


Functions return values to the calling statement to provide the result of the computation or
operation performed within the function. This allows the calling code to use the result for further
processing or decision-making.
function add(a, b) {
return a + b;
}
let result = add(3, 4); // result is 7

27. What is variable scope in JavaScript?


Variable scope in JavaScript determines the visibility and lifetime of a variable. There are two
main types of scope:
- Global scope: Variables declared outside of any function are in the global scope and can be
accessed from anywhere in the code.
- Local scope: Variables declared within a function are in the local scope and can only be accessed
within that function.

28. How are arrays created and manipulated in JavaScript?


Arrays in JavaScript are created using the array literal syntax or the `Array` constructor. They can
be manipulated using various methods and properties.
- Creation:
let fruits = ["Apple", "Banana", "Cherry"];
let numbers = new Array(1, 2, 3, 4, 5);

- Manipulation:
javascript
fruits.push("Dragonfruit"); // Adds to the end
fruits.pop(); // Removes from the end
fruits.unshift("Avocado"); // Adds to the beginning
fruits.shift(); // Removes from the beginning
let sliced = fruits.slice(1, 3); // Slices the array
fruits.splice(2, 1, "Blueberry"); // Removes and/or adds elements

29. What are Regular expressions and how are they used in JavaScript?
Regular expressions (regex) are patterns used to match character combinations in strings. In
JavaScript, they are used for pattern matching and searching within strings.
let regex = /hello/i; // 'i' for case-insensitive
let str = "Hello World";
let result = regex.test(str); // true

JAYANTI SHANKAR 6
3BSC WEB TECHNOLOGIES UNT3 NEP

30. What is the role of the `exec()` method in JavaScript regular expressions?

The `exec()` method in JavaScript executes a search for a match in a specified string. It returns an
array of matched results or `null` if no match is found.
let regex = /(\d+)/;
let str = "There are 123 apples";
let result = regex.exec(str); // ["123", "123"]

31. What are flags in regular expressions?


Flags in regular expressions are modifiers that change how the pattern is interpreted. Common
flags include:
- `g`: Global search.
- `i`: Case-insensitive search.
- `m`: Multi-line search.

let regex = /hello/gi; // Global, case-insensitive search

32. What is the role of objects in JavaScript, and how are they defined?

Objects in JavaScript are collections of key-value pairs. They are used to store data and more
complex entities. Objects can be defined using the object literal syntax or the `Object` constructor.

- Object literal:
let person = {
firstName: "John",
lastName: "Doe",
age: 30
};

- Object constructor:
let person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 30;

33. What are the Window and Frame objects used for in JavaScript?
- Window object: Represents the browser window and provides methods to control the browser
window, such as `alert()`, `confirm()`, and `prompt()`. It also serves as the global object, meaning all
global variables and functions are properties of the window.

- Frame object: Represents an HTML frame element. It is used to manipulate frame elements
within a frameset. Frames are now largely deprecated in favor of modern techniques like `iframe`
and CSS for layouts.
JAYANTI SHANKAR 7
3BSC WEB TECHNOLOGIES UNT3 NEP

34. Define Event. How events are handled in JavaScript.


An event is an action or occurrence detected by the browser, such as a user clicking a button,
submitting a form, or loading a page. Events are handled in JavaScript using event listeners or event
handlers, which execute code in response to events.
document.getElementById("myButton").addEventListener("click", function() {
alert("Button was clicked!");
});

35. What is exception handling, and how is it implemented in JavaScript?


Exception handling in JavaScript involves catching and handling errors using the `try...catch`
block. This allows the program to continue running even if an error occurs.

try {
let result = riskyOperation();
} catch (error) {
console.error("An error occurred: " + error.message);
} finally {
console.log("This will always run.");
}

36. What are the Boolean and Number objects in JavaScript?


- Boolean object: Wrapper for a boolean value. Created using the `Boolean` constructor.
let isTrue = new Boolean(true);
- Number object: Wrapper for numeric values. Created using the `Number` constructor.
let num = new Number(42);

37. What is JSON? How does JSON represent JavaScript objects as strings?
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for
humans to read and write and easy for machines to parse and generate. JSON is commonly used for
transmitting data in web applications between a server and a client.
How JSON Represents JavaScript Objects as Strings
JSON represents JavaScript objects as strings using a specific syntax. Here are the key points of
JSON syntax:
1. Objects: Represented as key-value pairs enclosed in curly braces {}.
2. Arrays: Ordered lists of values enclosed in square brackets [].
3. Values: Can be strings (enclosed in double quotes), numbers, objects, arrays, true, false, or
null.
4. Keys: Strings enclosed in double quotes

JAYANTI SHANKAR 8
3BSC WEB TECHNOLOGIES UNT3 NEP

Long Answer questions (4/5/6)

1. What is JavaScript? Write the benefits and problems with JavaScript.

JavaScript is a high-level, interpreted programming language primarily used to create dynamic and
interactive effects within web browsers. It is a key component of the web alongside HTML and CSS.

Benefits of JavaScript:
1. Client-Side Execution: Reduces server load and improves user experience by running directly in
the browser.
2. Interactivity: Enables dynamic content updates and interactive user interfaces.
3. Versatility: Can be used for both front-end (using frameworks like React, Angular) and back-end
development (using Node.js).
4. Large Ecosystem: Rich libraries and frameworks, extensive community support, and continuous
updates.
5. Easy to Learn: Has a straightforward syntax that is relatively easy for beginners to pick up.

Problems with JavaScript:


1. Browser Compatibility: Different browsers may implement JavaScript features differently, leading
to inconsistent behavior.
2. Security Issues: Vulnerable to certain types of attacks, such as cross-site scripting (XSS).
3. Client-Side Dependency: If JavaScript is disabled in the user's browser, certain functionalities
may not work.
4. Performance: Can be slower compared to compiled languages, especially for computation-
intensive tasks.
5. Lack of Type Checking: Dynamic typing can lead to runtime errors and bugs that are hard to
debug.

2. Explain the alternative solutions to JavaScript for making websites interactive and dynamic.
While JavaScript is the dominant language for web interactivity, there are alternative solutions and
technologies that can complement or substitute it in certain contexts:

1. WebAssembly (Wasm): A binary instruction format that runs at near-native speed. It allows
code written in other languages (like C, C++, Rust) to run on the web.
2. HTML5 and CSS3: These technologies provide advanced features like animations, transitions,
and responsive design without needing JavaScript.
3. Server-Side Rendering (SSR): Technologies like PHP, ASP.NET, and frameworks like Next.js
for React can render dynamic content on the server before sending it to the client.
4. Frameworks and Libraries: While still using JavaScript, frameworks like Angular, React, and
Vue.js provide more structured and efficient ways to create dynamic web applications.
5. Progressive Web Apps (PWAs): Use modern web capabilities to deliver app-like experiences.
They can work offline and offer better performance.

JAYANTI SHANKAR 9
3BSC WEB TECHNOLOGIES UNT3 NEP

3.Write Basics of JavaScript


1. Variables
Variables are used to store data values. JavaScript supports `var`, `let`, and `const` for variable
declarations.

2. Data Types
JavaScript supports several data types:
- Number: Represents both integer and floating-point numbers
- String: Represents a sequence of characters.
- Boolean: Represents true or false value
- Object: Represents a collection of properties.
- Array: Represents an ordered list of values.
javascript
let fruits = ["Apple", "Banana", "Cherry"];
- Undefined: Represents a variable that has been declared but not assigned a value.
- Null: Represents the intentional absence of any object value.

3. Operators
Operators are used to perform operations on variables and values.
- Arithmetic Operators: +, -, *, /, %, ++, -
- Comparison Operators: ==, ===, !=, !==, >, <, >=, <=
- Logical Operators: &&, ||, !
- Assignment Operators: =, +=, -=, *=, /=
4. Functions

5. Functions are blocks of code designed to perform a particular task. They are executed when
called.
- Function Declaration:
javascript
function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alice"));

- Function Expression:
javascript
const greet = function(name) {
return "Hello, " + name;
};
console.log(greet("Bob"));

5. Control Structures
Control structures control the flow of execution in a program.
- if..else Statement:
`- Switch Statement:
JAYANTI SHANKAR 10
3BSC WEB TECHNOLOGIES UNT3 NEP
- do..while Loop:

6. Events
JavaScript can react to events triggered by user actions or browser activity.
- Event Listener:

7. Comments
Comments are used to explain code and are ignored by the JavaScript engine.
- Single-line Comment:
javascript
// This is a single-line comment
- Multi-line Comment:
javascript
/* This is a
multi-line comment */

4. How do you declare and initialize variables in JavaScript?


In JavaScript, variables can be declared and initialized using three keywords: `var`, `let`, and `const`.
Each keyword has different scoping rules and use cases. Here's a detailed explanation of each:
Using `var`
The `var` keyword is used to declare a variable that can be globally or functionally scoped.
// Declaration
var name;
// Initialization
name = "John";
// Declaration and Initialization
var age = 30;

Using `let`
The `let` keyword is used to declare a block-scoped variable, which means it is only available within
the block where it is defined.
// Declaration
let city;
// Initialization
city = "New York";
// Declaration and Initialization
let country = "USA";

Using `const`
The `const` keyword is used to declare a block-scoped variable that cannot be reassigned once it is
initialized. However, if the variable holds an object, the properties of the object can be changed.
// Declaration and Initialization
const pi = 3.14;
// Attempting to reassign will cause an error
// pi = 3.14159; // Error: Assignment to constant variable.
const person = { name: "Alice", age: 25 };
JAYANTI SHANKAR 11
3BSC WEB TECHNOLOGIES UNT3 NEP
// Properties of the object can be changed
person.age = 26; // This is allowed

- Scope:
- `var` is function-scoped.
- `let` and `const` are block-scoped.

- Reassignment:
- Variables declared with `var` and `let` can be reassigned.
- Variables declared with `const` cannot be reassigned.

- Hoisting:
- `var` declarations are hoisted to the top of their scope and initialized with `undefined`.
- `let` and `const` declarations are hoisted but are not initialized, resulting in a "temporal dead
zone" until the declaration is encountered.

5. Explain various operators and data types available in JavaScript with examples.
Data Types:
1. Number: Represents both integers and floating-point numbers.
let age = 30;
let price = 19.99;
2. String: Represents a sequence of characters.
let name = "John Doe";
3. Boolean: Represents true or false values.
let isActive = true;
4. Object: Represents a collection of properties.
let person = { firstName: "John", lastName: "Doe" };
5. Array: Represents an ordered list of values.
let numbers = [1, 2, 3, 4, 5];
6. Undefined: Represents a variable that has been declared but not assigned a value.
let x;
7. Null: Represents the intentional absence of any object value.
let emptyValue = null;

Operators:
1. Arithmetic Operators: Perform basic mathematical operations.
javascript
let sum = 10 + 5; // Addition
let difference = 10 - 5; // Subtraction
let product = 10 * 5; // Multiplication
let quotient = 10 / 5; // Division
let remainder = 10 % 3; // Modulus

2. Comparison Operators: Compare two values and return a boolean.


javascript
JAYANTI SHANKAR 12
3BSC WEB TECHNOLOGIES UNT3 NEP
let isEqual = (10 == "10"); // true
let isIdentical = (10 === "10"); // false
let isGreater = (10 > 5); // true
let isLesser = (10 < 5); // false

3. Logical Operators: Perform logical operations.


javascript
let andResult = (true && false); // false
let orResult = (true || false); // true
let notResult = !true; // false

4. Assignment Operators: Assign values to variables.


javascript
let x = 10; // Assignment
x += 5; // Equivalent to x = x + 5
x -= 5; // Equivalent to x = x - 5

6. What are the string manipulation functions in JavaScript?


- length: Returns the length of a string.
javascript
let str = "Hello";
console.log(str.length); // 5

- toUpperCase(): Converts the string to uppercase.


javascript
let str = "hello";
console.log(str.toUpperCase()); // "HELLO"

- toLowerCase(): Converts the string to lowercase.


javascript
let str = "HELLO";
console.log(str.toLowerCase()); // "hello"

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


javascript
let str = "Hello";
console.log(str.charAt(1)); // "e"

- substring(): Extracts a part of a string.


javascript
let str = "Hello, World";
console.log(str.substring(0, 5)); // "Hello"

- split(): Splits a string into an array of substrings.


javascript
JAYANTI SHANKAR 13
3BSC WEB TECHNOLOGIES UNT3 NEP
let str = "Hello, World";
let arr = str.split(", "); // ["Hello", "World"]

- replace(): Replaces a substring with another substring.


javascript
let str = "Hello, World";
console.log(str.replace("World", "JavaScript")); // "Hello, JavaScript"

7. Describe the syntax and purpose of looping statements in JavaScript.


Looping statements in JavaScript allow code to be executed repeatedly based on a condition.
- for loop: Executes a block of code a specific number of times.
for (let i = 0; i < 5; i++) {
console.log(i);
}

- while loop: Executes a block of code as long as a specified condition is true.


let i = 0;
while (i < 5) {
console.log(i);
i++;
}

- do...while loop: Executes a block of code once, and then repeats the loop as long as a specified
condition is true.
javascript
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);

8. Explain if..else statement in JavaScript with syntax and example.


The `if..else` statement is used to execute code based on a condition.
Syntax:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}

Example:
let age = 20;
if (age >= 18) {
console.log("You are an adult.");
} else {
JAYANTI SHANKAR 14
3BSC WEB TECHNOLOGIES UNT3 NEP
console.log("You are a minor.");
}

9. Explain for loop in JavaScript with syntax and example.


The `for` loop in JavaScript is used to repeat a block of code a certain number of times. The loop
consists of three main parts: initialization, condition, and increment/decrement. Here’s the syntax
and an example to illustrate how it works.

Syntax
for (initialization; condition; increment/decrement) {
// Code to be executed
}
- Initialization: This part is executed once before the loop starts. It's typically used to initialize one or
more loop counters.
- Condition: This part is evaluated before each iteration of the loop. If it evaluates to `true`, the loop
statements execute. If it evaluates to `false`, the loop terminates.
- Increment/Decrement: This part is executed after each iteration of the loop. It’s typically used to
update the loop counter.
for (let i = 1; i <= 5; i++) {
console.log(i);
}

Explanation:
- Initialization: `let i = 1` initializes the loop counter `i` to 1.
- Condition: `i <= 5` is the condition that keeps the loop running as long as `i` is less than or equal to
5.
- Increment: `i++` increments the loop counter by 1 after each iteration.

Example with Array


Here’s another example that iterates over an array and prints each element:

let fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry"];

for (let i = 0; i < fruits.length; i++) {


console.log(fruits[i]);
}

Explanation:
- Initialization: `let i = 0` initializes the loop counter `i` to 0.
- Condition: `i < fruits.length` keeps the loop running as long as `i` is less than the length of the
`fruits` array.
- Increment: `i++` increments the loop counter by 1 after each iteration.
- Inside the loop, `console.log(fruits[i])` prints the element at the current index `i`.

JAYANTI SHANKAR 15
3BSC WEB TECHNOLOGIES UNT3 NEP
10. Explain switch statement in JavaScript with syntax and example.

The `switch` statement in JavaScript allows you to execute one block of code among many based on
the value of an expression. It's a cleaner way to handle multiple conditions compared to multiple
`if...else` statements.
Syntax
switch (expression) {
case value1:
// Code to be executed if expression === value1
break;
case value2:
// Code to be executed if expression === value2
break;
// You can have as many cases as needed
default:
// Code to be executed if expression doesn't match any case
}

let day = 3;
let dayName;

switch (day) {
case 1:
dayName = "Sunday";
break;
case 2:
dayName = "Monday";
break;
case 3:
dayName = "Tuesday";
break;
case 4:
dayName = "Wednesday";
break;
case 5:
dayName = "Thursday";
break;
case 6:
dayName = "Friday";
break;
case 7:
dayName = "Saturday";
break;
default:
dayName = "Invalid day";
}
JAYANTI SHANKAR 16
3BSC WEB TECHNOLOGIES UNT3 NEP

console.log(dayName); // Outputs: Tuesday

11. Describe break and continue with the help of an example.

`break` and `continue` are control statements used inside loops.


- `break` exits the loop immediately.
- `continue` skips the rest of the code inside the loop for the current iteration and moves to the next
iteration.
for (let i = 0; i < 10; i++) {
if (i === 3) {
break; // Exit the loop when i is 3
}
console.log(i); // Outputs: 0, 1, 2
}

for (let i = 0; i < 10; i++) {


if (i === 3) {
continue; // Skip the rest of the loop when i is 3
}
console.log(i); // Outputs: 0, 1, 2, 4, 5, 6, 7, 8, 9
}

12. Explain the different types of operators in JavaScript.


JavaScript provides several types of operators:

- Arithmetic Operators: Perform arithmetic operations like addition, subtraction, etc.


let x = 5 + 2; // Addition
let y = 5 - 2; // Subtraction
let z = 5 * 2; // Multiplication
let a = 5 / 2; // Division
let b = 5 % 2; // Modulus (remainder)

- Comparison Operators: Compare two values and return a boolean.


let x = 5 > 2; // Greater than
let y = 5 < 2; // Less than
let z = 5 >= 2; // Greater than or equal to
let a = 5 <= 2; // Less than or equal to
let b = 5 == 2; // Equal to
let c = 5 === 2;// Strict equal to
let d = 5 != 2; // Not equal to
let e = 5 !== 2;// Strict not equal to

JAYANTI SHANKAR 17
3BSC WEB TECHNOLOGIES UNT3 NEP

- Logical Operators: Perform logical operations.


let x = (5 > 2) && (5 < 10); // Logical AND
let y = (5 > 2) || (5 < 10); // Logical OR
let z = !(5 > 2); // Logical NOT

- Assignment Operators: Assign values to variables.


let x = 5; // Assign
x += 2; // Add and assign
x -= 2; // Subtract and assign
x *= 2; // Multiply and assign
x /= 2; // Divide and assign
x %= 2; // Modulus and assign

- Bitwise Operators: Perform bitwise operations.


let x = 5 & 1; // AND
let y = 5 | 1; // OR
let z = 5 ^ 1; // XOR
let a = ~5; // NOT
let b = 5 << 1; // Left shift
let c = 5 >> 1; // Right shift
let d = 5 >>> 1;// Unsigned right shift

- Ternary Operator: A shorthand for an `if...else` statement.


let x = (5 > 2) ? "Yes" : "No"; // Outputs: Yes

13. What is an Array and Explain the basic operations that are performed on arrays.
An array in JavaScript is a data structure used to store multiple values in a single variable. Arrays
can hold values of different types and are indexed starting from 0.

Basic Operations
- Create an Array:
let fruits = ["Apple", "Banana", "Cherry"];

- Access Elements:
let firstFruit = fruits[0]; // Access first element

- Modify Elements:
fruits[1] = "Blueberry"; // Modify second element

- Add Elements:
fruits.push("Date"); // Add to the end
fruits.unshift("Apricot"); // Add to the beginning

- Remove Elements:
JAYANTI SHANKAR 18
3BSC WEB TECHNOLOGIES UNT3 NEP
fruits.pop(); // Remove from the end
fruits.shift(); // Remove from the beginning

- Array Length:
let length = fruits.length; // Get the number of elements

14. Explain the basic procedure and algorithm for the removal of an array element.
If you know the index of the element you want to remove, you can use the `splice` method. The
`splice` method changes the contents of an array by removing or replacing existing elements and/or
adding new elements in place.
# Algorithm
1. Find the index of the element you want to remove.
2. Use the `splice` method to remove the element at the specified index.
# Procedure
let fruits = ["Apple", "Banana", "Cherry", "Date"];
// Let's say we want to remove the element at index 1 ("Banana")
let index = 1;
if (index > -1) {
fruits.splice(index, 1);
}
console.log(fruits); // Outputs: ["Apple", "Cherry", "Date"]

Removing an Element by Value


If you know the value of the element you want to remove, you can first find the index of the element
using the `indexOf` method, and then use `splice` to remove it.

# Algorithm
1. Use the `indexOf` method to find the index of the element.
2. If the element is found (i.e., the index is not -1), use the `splice` method to remove it.
# Procedure
let fruits = ["Apple", "Banana", "Cherry", "Date"];
// Let's say we want to remove the element "Banana"
let valueToRemove = "Banana";
let index = fruits.indexOf(valueToRemove);
if (index > -1) {
fruits.splice(index, 1);
}
console.log(fruits); // Outputs: ["Apple", "Cherry", "Date"]

Removing All Instances of a Value


If you want to remove all instances of a value from an array, you can use a loop in conjunction with
`indexOf` and `splice`.
# Algorithm
1. Initialize a loop to find the index of the value using `indexOf`.
2. If the element is found (i.e., the index is not -1), use `splice` to remove it.
3. Continue the loop until no more instances are found.
JAYANTI SHANKAR 19
3BSC WEB TECHNOLOGIES UNT3 NEP
# Procedure
let fruits = ["Apple", "Banana", "Cherry", "Banana", "Date"];
// Let's say we want to remove all instances of "Banana"
let valueToRemove = "Banana";
let index = fruits.indexOf(valueToRemove);
while (index > -1) {
fruits.splice(index, 1);
index = fruits.indexOf(valueToRemove); // Find the next instance
}
console.log(fruits); // Outputs: ["Apple", "Cherry", "Date"]

Using the `filter` Method


Alternatively, you can use the `filter` method to create a new array that excludes the element you
want to remove. This method is useful for removing all instances of a value.
# Algorithm
1. Use the `filter` method to create a new array that includes all elements except the one(s) you want
to remove.
# Procedure
let fruits = ["Apple", "Banana", "Cherry", "Banana", "Date"];
// Let's say we want to remove all instances of "Banana"
let valueToRemove = "Banana";
fruits = fruits.filter((fruit) => fruit !== valueToRemove);
console.log(fruits); // Outputs: ["Apple", "Cherry", "Date"]

20. Explain the functioning of the JavaScript keyword `this` and the dot operator.

# `this` Keyword
The `this` keyword refers to the object it belongs to. Its value depends on the context in which it is
used:

- Global Context: In the global execution context (outside of any function), `this` refers to the global
object (in browsers, `window`).
console.log(this); // Window object in browsers

- Function Context: Inside a function, `this` refers to the global object (in non-strict mode) or
`undefined` (in strict mode).
function showThis() {
console.log(this);
}
showThis(); // Window object (undefined in strict mode)

- Object Method: When a function is called as a method of an object, `this` refers to the object.
let obj = {
name: "Alice",
greet: function() {
console.log(this.name);
JAYANTI SHANKAR 20
3BSC WEB TECHNOLOGIES UNT3 NEP
}
};
obj.greet(); // Alice

- Constructor: When a function is used as a constructor with the `new` keyword, `this` refers to the
new instance created.
function Person(name) {
this.name = name;
}
let person = new Person("Bob");
console.log(person.name); // Bob

- Arrow Functions: In arrow functions, `this` retains the value from the enclosing lexical context.
let obj2 = {
name: "Charlie",
greet: () => {
console.log(this.name);
}
};
obj2.greet(); // undefined (in non-strict mode, it will be `window.name` if `window.name` is defined)

# Dot Operator
The dot operator (.) is used to access properties and methods of an object.

let car = {
brand: "Toyota",
model: "Corolla",
start: function() {
console.log("Car started");
}
};

console.log(car.brand); // Toyota
car.start(); // Car started

21. Describe the role and functionality of the Document Object Model (DOM) in JavaScript.
The Document Object Model (DOM) is a programming interface for web documents. It represents
the page so that programs can change the document structure, style, and content. The DOM
represents the document as nodes and objects; that way, programming languages can interact with
the page.

# Key Functions of the DOM:


- Access and Modify HTML Elements: JavaScript can access and modify the content, structure, and
style of HTML elements.

JAYANTI SHANKAR 21
3BSC WEB TECHNOLOGIES UNT3 NEP
- Event Handling: JavaScript can attach event handlers to HTML elements, allowing for interactive
web pages.
- Traverse the DOM: JavaScript can navigate through the document tree, finding elements by their
tag name, ID, class name, etc.

<!DOCTYPE html>
<html>
<body>

<h1 id="myHeader">Hello World!</h1>


<button onclick="changeText()">Click me</button>

<script>
function changeText() {
let header = document.getElementById("myHeader");
header.innerHTML = "Hello JavaScript!";
}
</script>
</body>
</html>

22. What are the key differences between traditional object-oriented languages and
JavaScript's approach to objects?
# Key Differences:
1. Prototypal Inheritance vs. Classical Inheritance:
- Traditional OOP: Uses class-based inheritance where classes define blueprints for objects, and
objects are instances of classes.
- JavaScript: Uses prototypal inheritance where objects inherit directly from other objects. Objects
can be created and extended without the need for classes.

2. Classes:
- Traditional OOP: Classes are a core concept.
- JavaScript: Until ES6, there were no classes. ES6 introduced `class` syntax, but it is syntactic
sugar over the prototypal inheritance model.

3. Constructor Functions:
- Traditional OOP: Constructors are special methods defined within classes.
- JavaScript: Constructors are regular functions invoked with the `new` keyword.

4. Encapsulation:
- Traditional OOP: Strong support for encapsulation with access modifiers (public, private,
protected).
- JavaScript: Encapsulation is achieved through closures and private fields (introduced in ES6).

JAYANTI SHANKAR 22
3BSC WEB TECHNOLOGIES UNT3 NEP
23. Explain about exception handling in JavaScript.
Exception handling in JavaScript is done using the `try...catch` statement, which allows you to test a
block of code for errors, handle them, and execute cleanup code if necessary.
# Syntax
try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
} finally {
// Code to be executed regardless of an error
}

# Example
try {
let result = someFunction(); // This may throw an error
console.log(result);
} catch (error) {
console.log("An error occurred:", error.message);
} finally {
console.log("This will always run");
}

24. Explain about regular expressions.


Regular expressions (regex) are patterns used to match character combinations in strings. They are
powerful tools for searching, matching, and manipulating text. In JavaScript, regular expressions are
implemented through the `RegExp` object.

# Syntax
Regular expressions are created using:
- Literal notation: Enclosed within slashes.
let regex = /pattern/flags;
- Constructor notation: Using the `RegExp` constructor.
javascript
let regex = new RegExp('pattern', 'flags');

# Flags
- `g`: Global search
- `i`: Case-insensitive search
- `m`: Multi-line search
- `u`: Unicode; treat pattern as a sequence of Unicode code points
- `y`: Sticky; matches starting at the current position in the target string
# Example
let regex = /hello/i;
let str = "Hello World!";
let result = regex.test(str); // true

JAYANTI SHANKAR 23
3BSC WEB TECHNOLOGIES UNT3 NEP
# Common Methods
- `test`: Tests for a match in a string. Returns `true` or `false`.
let regex = /world/;
regex.test("Hello world!"); // true
- `exec`: Executes a search for a match in a string. Returns an array of results or `null`.

let regex = /world/;


regex.exec("Hello world!"); // ["world"]

25. Explain about built-in objects in JavaScript.

JavaScript provides several built-in objects that offer various functionalities for performing different
tasks.
# Examples of Built-in Objects:
- `String`: Provides methods for string manipulation.
let str = "Hello, World!";
console.log(str.toUpperCase()); // "HELLO, WORLD!"

- `Number`: Provides methods for number manipulation.


let num = 123.456;
console.log(num.toFixed(2)); // "123.46"

- `Array`: Provides methods for array manipulation.


let arr = [1, 2, 3];
arr.push(4);
console.log(arr); // [1, 2, 3, 4]

- `Date`: Provides methods for date and time manipulation.


let now = new Date();
console.log(now.toDateString()); // "Mon Jun 21 2024"

- `Math`: Provides properties and methods for mathematical constants and functions.
let random = Math.random(); // Random number between 0 and 1
let pi = Math.PI; // 3.141592653589793

- `RegExp`: Provides methods for working with regular expressions.


let regex = /world/;
console.log(regex.test("Hello world!")); // true

26. What are the functions used to manipulate regular expressions in JavaScript, and which
classes do they belong to?
The primary functions used to manipulate regular expressions belong to the `RegExp` class and the
`String` class.
# `RegExp` Methods:
- `test`: Tests for a match in a string. Returns `true` or `false`.
let regex = /world/;
JAYANTI SHANKAR 24
3BSC WEB TECHNOLOGIES UNT3 NEP
regex.test("Hello world!"); // true

- `exec`: Executes a search for a match in a string. Returns an array of results or `null`.
let regex = /world/;
regex.exec("Hello world!"); // ["world"]

# `String` Methods:
- `match`: Retrieves the matches when matching a string against a regular expression.
let str = "Hello world!";
let result = str.match(/world/); // ["world"]

- `replace`: Replaces matches in a string with a replacement.


let str = "Hello world!";
let newStr = str.replace(/world/, "JavaScript"); // "Hello JavaScript!"

- `search`: Searches a string for a match against a regular expression and returns the index of the
match.
let str = "Hello world!";
let index = str.search(/world/); // 6

- `split`: Splits a string into an array of substrings based on a regular expression.


let str = "Hello world!";
let parts = str.split(/ /); // ["Hello", "world!"]

27. What are the main functions used in JavaScript for string manipulation with regular
expressions?
The main functions used for string manipulation with regular expressions in JavaScript are methods
of the `String` object:
- `String.prototype.match`: Retrieves the matches when matching a string against a regular
expression.
let str = "Hello world!";
let matches = str.match(/world/); // ["world"]

- `String.prototype.replace`: Replaces matches in a string with a replacement.


let str = "Hello world!";
let newStr = str.replace(/world/, "JavaScript"); // "Hello JavaScript!"

- `String.prototype.search`: Searches a string for a match against a regular expression and returns the
index of the match.
let str = "Hello world!";
let index = str.search(/world/); // 6

- `String.prototype.split`: Splits a string into an array of substrings based on a regular expression.


let str = "Hello world!";
let parts = str.split(/ /); // ["Hello", "world!"]

JAYANTI SHANKAR 25
3BSC WEB TECHNOLOGIES UNT3 NEP

28. Explain the concept of event handlers in JavaScript.


Event handlers are functions that are executed when a specific event occurs. They are used to make
web pages interactive by responding to user actions like clicks, mouse movements, key presses, and
more.

# Adding Event Handlers


- Inline Event Handlers: Directly in the HTML element.
<button onclick="alert('Button clicked!')">Click me</button>

- DOM Properties: Assigning a function to an event property of a DOM element.


let button = document.getElementById("myButton");
button.onclick = function() {
alert('Button clicked!');
};

- `addEventListener` Method: Attaching multiple event handlers to a single element.


let button = document.getElementById("myButton");
button.addEventListener("click", function() {
alert('Button clicked!');
});

# Example
<!DOCTYPE html>
<html>
<body>
<button id="myButton">Click me</button>
<script>
document.getElementById("myButton").addEventListener("click", function() {
alert('Button clicked!');
});
</script>

</body>
</html>

JAYANTI SHANKAR 26

You might also like