0% found this document useful (0 votes)
3 views12 pages

wt_unit3

The document outlines key differences between Java and JavaScript, highlighting aspects such as typing, execution, and syntax. It explains JavaScript's benefits, problems, and its support for object-oriented programming, along with various array methods, DOM manipulation, and user input handling. Additionally, it provides examples of JavaScript functions, event handling, and validation techniques, alongside practical coding examples for sorting, factorial computation, and form validation.

Uploaded by

Rakshith N
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)
3 views12 pages

wt_unit3

The document outlines key differences between Java and JavaScript, highlighting aspects such as typing, execution, and syntax. It explains JavaScript's benefits, problems, and its support for object-oriented programming, along with various array methods, DOM manipulation, and user input handling. Additionally, it provides examples of JavaScript functions, event handling, and validation techniques, alongside practical coding examples for sorting, factorial computation, and form validation.

Uploaded by

Rakshith N
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/ 12

Detailed Answers with Explanations and Code Examples

1. Describe three major differences between Java and JavaScript.


Aspect Java JavaScript

Type Object-Oriented Programming Language Object-Based Scripting Language

Compiled (runs on JVM or browser with


Execution Interpreted (runs directly in browser)
plugin)

Loosely typed (type inferred at


Typing Strongly typed (variables must declare type)
runtime)

Standalone Standalone applications possible Needs to be embedded in HTML

Syntax More complex, similar to C++ Simpler, easier to learn

File
.java .js
Extension

Memory Consumes more memory Lightweight, less memory usage

Platform Platform-independent via JVM Platform-independent via browser [1]

2. What is JavaScript? List its benefits and problems. Are OOP concepts
incorporated in JavaScript? How are objects handled in it?
JavaScript is a lightweight, interpreted scripting language primarily used to create dynamic and
interactive effects within web browsers.
Benefits:
Simple and easy to learn [2]
Fast execution (client-side)
Reduces server load (validates data in browser)
Highly interoperable (can be embedded in HTML and other languages)
Enables dynamic, interactive web pages
Problems:
Security risks (runs on client, can be exploited)
Browser compatibility issues for some features
No support for multithreading or multiprocessing
Source code is visible to users
OOP Concepts in JavaScript:
JavaScript supports object-oriented programming, including encapsulation, inheritance (via
prototypes), and, from ES6, classes [3] .
Objects are created using object literals, constructor functions, or ES6 classes.
Object Handling Example:

// Object literal
let person = {
name: "Alice",
greet: function() { console.log("Hello, " + this.name); }
};
person.greet();

// Constructor function
function Car(model) {
this.model = model;
}
let car1 = new Car("Toyota");
console.log(car1.model);

// ES6 class
class Animal {
constructor(type) { this.type = type; }
}
let dog = new Animal("Dog");
console.log(dog.type);

3. What are the major uses of JavaScript on the client side?


Form validation (e.g., checking user input before submitting a form)
Dynamic content updates without reloading the page (AJAX)
Manipulating HTML and CSS (DOM manipulation)
Creating interactive effects (sliders, pop-ups, animations)
Handling browser events (clicks, mouse movement, keyboard input)
Storing data locally (localStorage, sessionStorage)
Building Single Page Applications (SPAs)

4. Explain different primitive types in JavaScript.


JavaScript has seven primitive data types:
String: Textual data, e.g., "hello"
Number: Numeric values, e.g., 42, 3.14
BigInt: Large integers, e.g., 12345678901234567890n
Boolean: Logical values, true or false
Undefined: Variable declared but not assigned a value
Null: Intentional absence of any value
Symbol: Unique and immutable value, often used as object property keys
Example:

let name = "John"; // String


let age = 30; // Number
let bigNum = 9007199254740991n; // BigInt
let isStudent = false; // Boolean
let x; // Undefined
let y = null; // Null
let sym = Symbol("id"); // Symbol

5. Explain JavaScript Array methods with examples.


push(): Adds element(s) to end
let arr = [1, 2];
arr.push(3); // [1, 2, 3]

pop(): Removes last element


arr.pop(); // [1, 2]

shift(): Removes first element


arr.shift(); // [^2]

unshift(): Adds element(s) to start


arr.unshift(0); // [0, 2]

concat(): Combines arrays


let arr2 = [3, 4];
let combined = arr.concat(arr2); // [0, 2, 3, 4]

slice(): Returns selected elements


let sub = arr.slice(0, 1); // [^0]

splice(): Adds/removes elements


arr.splice(1, 0, 1.5); // [0, 1.5, 2]
forEach(): Iterates over array
arr.forEach(item => console.log(item));

map(): Returns new array with results of function


let squared = arr.map(x => x * x);

filter(): Returns elements matching condition


let even = arr.filter(x => x % 2 === 0);

reduce(): Reduces array to single value


let sum = arr.reduce((a, b) => a + b, 0);

6. Describe the two ways to embed JavaScript in an HTML document.


Internal (inline):
<script>
alert("Hello from internal script!");
</script>

External:
<script src="script.js"></script>

7. Explain the concept of object creation and modification in JavaScript.


Object creation:
Object literal:
let obj = { name: "Alice", age: 25 };

Constructor function:
function Person(name) { this.name = name; }
let p = new Person("Bob");

ES6 class:
class Car { constructor(model) { this.model = model; } }
let myCar = new Car("Honda");

Modification:
Add or update property:
obj.city = "Bangalore";
obj.age = 26;

Delete property:
delete obj.city;

8. Explain with examples, screen output and keyboard input.


Screen Output:
alert("Hello!");

document.write("Welcome to JavaScript!");

console.log("Debug info");

document.getElementById("output").innerText = "Result";

Keyboard Input:
prompt() for user input:
let name = prompt("Enter your name:");
alert("Hello, " + name);

9. Explain pattern matching using regular expressions in JavaScript with example.


Regular expressions are patterns used to match character combinations in strings.
Syntax:

let pattern = /abc/;


let result = pattern.test("abcdef"); // true

Example 1: Validate Email

let email = "[email protected]";


let regex = /^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/;
console.log(regex.test(email)); // true

Example 2: Replace Digits

let str = "My number is 12345";


let newStr = str.replace(/\d/g, "X");
console.log(newStr); // "My number is XXXXX"
Example 3: Extract Words

let text = "JavaScript is fun!";


let words = text.match(/\w+/g);
console.log(words); // ["JavaScript", "is", "fun"]

Example 4: Search for a word

let sentence = "Hello World!";


let found = sentence.search(/world/i); // returns 6 (index of match)

10. Which are the methods used for accepting inputs from the keyboard and for
displaying outputs on the screen?
Input: prompt()
Output: alert(), document.write(), console.log(), and updating DOM elements

11. Write the difference between following pairs of methods in JavaScript:


i) pop() and unshift()
pop(): Removes and returns the last element of an array.
let arr = [1,2,3];
arr.pop(); // returns 3, arr is now [1,2]

unshift(): Adds one or more elements to the beginning of an array and returns the new
length.
arr.unshift(0); // returns 3, arr is now [0,1,2]

ii) match() and search()


match(): Returns an array of all matches of a regex in a string.
"abc123".match(/\d+/); // ["123"]

search(): Returns the index of the first match of a regex in a string, or -1 if not found.
"abc123".search(/\d+/); // 3
12. Explain the interactive dialogue boxes used in JavaScript.
alert(): Displays a message with an OK button.
alert("This is an alert!");

confirm(): Displays a message with OK and Cancel buttons, returns true/false.


let result = confirm("Are you sure?");

prompt(): Displays a message with a text box for user input, returns the input or null.
let name = prompt("Enter your name:");

13. Give examples for the different ways an array object can be created in
JavaScript, and also write HTML document and JavaScript code to sort 'N' given
values using a sorting technique.
Array Creation:

let arr1 = [1, 2, 3]; // Array literal


let arr2 = new Array(4, 5, 6); // Array constructor
let arr3 = Array.of(7, 8, 9); // Array.of method

Sorting Example (HTML + JS):

<!DOCTYPE html>
<html>
<body>
<input id="numbers" value="4,2,7,1,5">
<button onclick="sortNumbers()">Sort</button>
<div id="result"></div>
<script>
function sortNumbers() {
let input = document.getElementById('numbers').value;
let arr = input.split(',').map(Number);
arr.sort((a, b) => a - b);
document.getElementById('result').innerText = arr.join(', ');
}
</script>
</body>
</html>
14. Describe functions in JavaScript. Write an HTML document and JavaScript
function to compute and print factorial of a number, reverse a number, and
generate Fibonacci numbers.
Function Examples:

function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}

function reverseNumber(n) {
return Number(String(n).split('').reverse().join(''));
}

function fibonacci(n) {
let arr = [0, 1];
for (let i = 2; i < n; i++) arr[i] = arr[i - 1] + arr[i - 2];
return arr.slice(0, n);
}

HTML Example:

<!DOCTYPE html>
<html>
<body>
<input id="num" type="number">
<button onclick="showResults()">Compute</button>
<div id="output"></div>
<script>
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
function reverseNumber(n) {
return Number(String(n).split('').reverse().join(''));
}
function fibonacci(n) {
let arr = [0, 1];
for (let i = 2; i < n; i++) arr[i] = arr[i - 1] + arr[i - 2];
return arr.slice(0, n);
}
function showResults() {
let n = parseInt(document.getElementById('num').value);
let fact = factorial(n);
let rev = reverseNumber(n);
let fib = fibonacci(n);
document.getElementById('output').innerHTML =
"Factorial: " + fact + "<br>" +
"Reverse: " + rev + "<br>" +
"Fibonacci: " + fib.join(', ');
}
</script>
</body>
</html>

15. Write a JavaScript code that displays the text "REVA UNIVERSITY" with
increasing font size in the interval of 100ms in blue color when the font size
reaches 50pt, it should stop increasing.

<!DOCTYPE html>
<html>
<body>
<div id="text" style="color:blue;">REVA UNIVERSITY</div>
<script>
let size = 10;
let interval = setInterval(function() {
if (size >= 50) clearInterval(interval);
document.getElementById('text').style.fontSize = size + 'pt';
size++;
}, 100);
</script>
</body>
</html>

16. Write a program in JavaScript to accept three numbers using prompt and
calculate the largest of three numbers.

let a = parseFloat(prompt("Enter first number:"));


let b = parseFloat(prompt("Enter second number:"));
let c = parseFloat(prompt("Enter third number:"));
let largest = Math.max(a, b, c);
alert("The largest number is: " + largest);

17. Create a form for collecting student details and create a JavaScript code to
check the Name of the student with less than 50 characters and it should accept
only English alphabetic characters.

<!DOCTYPE html>
<html>
<body>
<form onsubmit="return validate()">
Name: <input type="text" id="name"><br>
<input type="submit" value="Submit">
</form>
<script>
function validate() {
let name = document.getElementById('name').value;
if (name.length > 50) {
alert("Name must be less than 50 characters");
return false;
}
if (!/^[a-zA-Z]+$/.test(name)) {
alert("Name must contain only alphabets");
return false;
}
return true;
}
</script>
</body>
</html>

18. Explain various methods in JavaScript to access DOM Nodes with examples.
getElementById: Selects an element by its ID.
let el = document.getElementById('myId');

getElementsByClassName: Selects all elements with a specific class.


let items = document.getElementsByClassName('myClass');

getElementsByTagName: Selects all elements with a given tag.


let divs = document.getElementsByTagName('div');

querySelector: Selects the first element matching a CSS selector.


let el = document.querySelector('.myClass');

querySelectorAll: Selects all elements matching a CSS selector.


let els = document.querySelectorAll('div > p');

19. A client is a web browser through which users make requests... Explain the
difference between client and server.
Client (Web Browser) Server

Initiates requests for resources/services Responds to client requests

Runs on user's device Runs on remote machine or cloud

Handles UI, user input, rendering Handles data processing, storage, business logic

Example: Chrome, Firefox, Edge Example: Apache, Node.js, IIS


20. Describe the different ways to embed JavaScript in HTML document.
Internal: Use <script> tags within HTML.
External: Link to a .js file using <script src="file.js"></script>.

21. Explain the various ways of linking JavaScript code with HTML documents.
Directly in HTML: Using <script> tags in the <head> or <body>.
External File: Using <script src="filename.js"></script> in the HTML.

22. Explain the Essential Document Object Methods with examples.


getElementById(): Selects an element by ID.
getElementsByClassName(): Selects elements by class.
getElementsByTagName(): Selects elements by tag.
createElement(): Creates a new element.
let p = document.createElement('p');

appendChild(): Adds a node as the last child.


document.body.appendChild(p);

querySelector(): Selects the first element matching a selector.


write(): Writes HTML or text to the document.

23. Explain the concept of object creation and modification of an array in


JavaScript. With suitable example, explain how to access the object properties.
Object Creation in Array:

let arr = [{id: 1, name: "Alice"}, {id: 2, name: "Bob"}];

Modification:

arr[^0].name = "Alicia";

Accessing Properties:

let name = arr[^0].name; // "Alicia"

Updating an object in array:


arr = arr.map(obj => obj.id === 2 ? {...obj, name: "Bobby"} : obj);

24. Explain Empty Field Validation and Number Validation with suitable example.
Empty Field Validation:
if (input.value === "") {
alert("Field cannot be empty");
}

Number Validation:
let age = input.value;
if (isNaN(age) || age < 1 || age > 100) {
alert("Enter a valid age between 1 and 100");
}

25. Explain the following two classes of Event: (1) Form Events (2) Mouse Events
Form Events: Triggered by user interaction with forms (e.g., onsubmit, onchange, oninput).
Mouse Events: Triggered by mouse actions (e.g., onclick, onmouseover, onmouseout,
onmousedown, onmouseup).

26. Write a program in JavaScript to accept three numbers using prompt and
calculate the largest of three numbers.

let a = parseFloat(prompt("Enter first number:"));


let b = parseFloat(prompt("Enter second number:"));
let c = parseFloat(prompt("Enter third number:"));
let largest = Math.max(a, b, c);
alert("The largest number is: " + largest);

If you need even more detail or code for any specific question, let me know the question
number.

1. WhatsApp-Image-2025-05-11-at-19.15.12-1.jpg
2. WhatsApp-Image-2025-05-11-at-19.15.12.jpg
3. WhatsApp-Image-2025-05-11-at-19.15.13.jpg

You might also like