JavaScript Complete Exam Material
JavaScript Complete Exam Material
2. Object-Oriented
3. Client-Side Execution
4. Event-Driven
5. Platform Independent
6. Case Sensitive
7. Dynamic Typing
Q b) List six types of values in JavaScript:
<script>
let sum = 0;
if (i % 2 !== 0) sum += i;
</script>
|----------------|-------------------------------|------------------------|
Example:
let person = {
};
Arithmetic: +, -, *, /
<script>
document.write(num + "<br>");
num += 2;
count++;
</script>
Example:
let name = prompt("Enter your name:", "Guest");
<script>
</script>
<script>
</script>
Example break:
if (i == 5) break;
document.write(i + "<br>");
Example continue:
if (i == 3) continue;
document.write(i + "<br>");
Functions are declared using the function keyword and can accept parameters and return
values.
Syntax:
function functionName(parameter1, parameter2) {
// code to be executed
}
You can call a function using:
functionName(arg1, arg2);
2. Anonymous Function:
var display = function() {
console.log("This is an anonymous function.");
};
display();
pop():
The pop() method removes the last element from an array.
Example:
let fruits = ['Apple', 'Banana', 'Mango'];
fruits.pop(); // ['Apple', 'Banana']
Q2b) Create a function that takes a string as input, process it and returns
the reversed string.
function reverseString(str) {
return str.split('').reverse().join('');
}
let reversed = reverseString("hello");
console.log(reversed); // Output: "olleh"
Q3c) Write a four point difference between group of check-box and group
of radio buttons.
| Feature | Checkboxes | Radio Buttons |
|-----------------------|--------------------------------------------|---------------------------------------------|
| Selection | Allows multiple selections | Only one selection at a time |
| Input Type | <input type="checkbox"> | <input type="radio"> |
| Use Case | For choosing multiple options | For choosing one option from a
group |
| Grouping | Work independently | Grouped using same name attribute
|
Example:
let person = {
name: "John",
age: 30
};
with (person) {
console.log(name); // John
console.log(age); // 30
}
Example:
function greet(name) {
console.log("Hello " + name);
}
greet("John"); // Output: Hello John
Q6d) Write a JavaScript that find and displays number of duplicate values
in an array.
function findDuplicates(arr) {
let counts = {};
let duplicates = [];
2. constructor:
Returns the function that created the array's prototype.
Example:
let arr = [1, 2, 3];
console.log(arr.constructor); // function Array()...
Q8a) Write a java script to convert string to number.
let str = "123";
let num1 = Number(str);
let num2 = parseInt(str);
let num3 = +str;
console.log(num1); // 123
console.log(num2); // 123
console.log(num3); // 123
Example:
<input type="text" id="username" name="username">
Types of Scope:
1. Global Scope – A variable declared outside any function.
2. Local Scope – A variable declared inside a function.
3. Block Scope – Introduced in ES6 using let and const.
Example:
var globalVar = "I am global"; // Global Scope
function test() {
var localVar = "I am local"; // Local Scope
if(true){
let blockVar = "I am block scoped"; // Block Scope
console.log(blockVar);
}
console.log(localVar);
}
console.log(globalVar);
Q4b) Write a javascript to create three categories Fruit, Flower and Color,
based on the selection of category the items in the option list must get
changed.
<select id="category" onchange="updateItems()">
<option value="Fruit">Fruit</option>
<option value="Flower">Flower</option>
<option value="Color">Color</option>
</select>
<select id="items"></select>
<script>
function updateItems() {
let category = document.getElementById("category").value;
let items = document.getElementById("items");
items.innerHTML = "";
let data = {
Fruit: ["Apple", "Banana", "Mango"],
Flower: ["Rose", "Lily", "Tulip"],
Color: ["Red", "Green", "Blue"]
};
data[category].forEach(item => {
let option = document.createElement("option");
option.text = item;
items.add(option);
});
}
</script>
Q5b) Give syntax of the use of "with" statement clause in JavaScript using
suitable example.
Syntax:
with (object) {
statement;
}
Example:
let person = {name: "John", age: 25};
with (person) {
console.log(name); // John
console.log(age); // 25
}
Q6b) Write HTML script that displays dropdown list containing options
Hyderabad, Pune, Nagpur. Write proper JavaScript such that when user
selects any options corresponding description of city and image of the city
appear in table below on the same page.
<select id="cities" onchange="showInfo()">
<option value="Hyderabad">Hyderabad</option>
<option value="Pune">Pune</option>
<option value="Nagpur">Nagpur</option>
</select>
<table border="1" id="cityTable">
<tr>
<td id="desc"></td>
<td><img id="cityImg" width="100"></td>
</tr>
</table>
<script>
function showInfo() {
let city = document.getElementById("cities").value;
let desc = document.getElementById("desc");
let img = document.getElementById("cityImg");
let info = {
Hyderabad: ["Hyderabad is known as the City of Pearls.", "hyderabad.jpg"],
Pune: ["Pune is a cultural capital of Maharashtra.", "pune.jpg"],
Nagpur: ["Nagpur is famous for oranges and central location.", "nagpur.jpg"]
};
desc.innerText = info[city][0];
img.src = info[city][1];
}
</script>
Common uses:
- User login and registration
- Feedback and contact forms
- Online surveys
- Data collection interfaces
Q7c) Write a java script to create user and password field and verify using
script.
<input type="text" id="user" placeholder="Username">
<input type="password" id="pass" placeholder="Password">
<button onclick="validate()">Login</button>
<script>
function validate() {
let u = document.getElementById("user").value;
let p = document.getElementById("pass").value;
if (u === "admin" && p === "1234") {
alert("Login successful");
} else {
alert("Invalid credentials");
}
}
</script>
Q8b) Create a function that takes a string as input, process it and returns
the reversed string.
function reverseString(str) {
return str.split("").reverse().join("");
}
console.log(reverseString("JavaScript"));
onChange:
Triggered when the value of an element changes.
Example:
<select onchange="alert('Changed')">
<option>One</option>
<option>Two</option>
</select>
Q9b) Create a javascript where a keypress event updates a label
dynamically with the pressed key and change the background color.
<input type="text" onkeypress="updateLabel(event)">
<label id="keyLabel">Pressed Key: </label>
<script>
function updateLabel(event) {
document.getElementById("keyLabel").innerText = "Pressed Key: " + event.key;
document.body.style.backgroundColor = "#" +
Math.floor(Math.random()*16777215).toString(16);
}
</script>
Syntax:
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2025 12:00:00 UTC; path=/";
Example:
<script>
document.cookie = "user=Admin; expires=Sat, 31 Dec 2025 12:00:00 UTC; path=/";
</script>
Q2c) Write a function that prompt the user for a color and uses what they
select to set the background color of the new webpage opened.
<script>
function openColorPage() {
let color = prompt("Enter a color:");
let newWindow = window.open("", "_blank", "width=400,height=300");
newWindow.document.write(`<body style='background-color:${color};'><h1>New
Page</h1></body>`);
}
</script>
Example:
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2025 12:00:00 UTC; path=/";
Q3b) Write a function that prompts the user for select color and what
they select to set the background color of the new webpage opened.
<script>
function setColorPage() {
let color = prompt("Enter a color:");
let win = window.open("", "_blank", "width=400,height=400");
win.document.write("<body style='background-color:" + color + ";'><h2>Color
Set!</h2></body>");
}
</script>
Q3c) Write the syntax and explain use of following methods of JavaScript
Timing Event
i) setTimeout()
ii) setInterval()
i) setTimeout(): Executes a function once after a specific delay (in milliseconds).
Syntax: setTimeout(function, milliseconds);
Example:
setTimeout(() => alert("Hello after 3 seconds"), 3000);
Example:
window.open("https://example.com", "_blank", "width=600,height=400");
Example:
document.cookie = "username=Jane; expires=Sat, 31 Dec 2025 12:00:00 UTC; path=/";
Q5b) Write a function that prompts the user for a color and uses what
they select to set the background color of the new webpage opened.
<script>
function changeBackgroundColor() {
let color = prompt("Enter your favorite color:");
let newWin = window.open("", "_blank", "width=500,height=400");
newWin.document.write(`<body
style="background-color:${color};"><h1>Welcome!</h1></body>`);
}
</script>
2. exec(): Executes a search for a match in a string and returns an array of information.
Example: /\d+/.exec('Year 2025'); // returns ['2025']
c) State and explain the process to make the rollover more efficient.
To make rollover more efficient:
1. Preload the images to avoid delays.
2. Use onmouseover and onmouseout events to switch images.
3. Use CSS and JavaScript together to enhance performance and reduce flicker.
a) Write a javascript in which when user rollover the name of fruit, the
corresponding image should be display.
<html><body>
<p onmouseover="document.getElementById('img').src='apple.jpg'">Apple</p>
<p onmouseover="document.getElementById('img').src='banana.jpg'">Banana</p>
<img id='img' src='' width='100'>
</body></html>
<iframe> embeds a document inside another. Attributes: src, width, height, frameborder.
Example:
<iframe src='page.html' width='300' height='200' frameborder='0'></iframe>
c) State the use of rollover & write a method used most commonly during
rollover.
Rollover is used to change an element’s appearance or image when a user hovers the mouse
over it.
a) Explain how to set the frame border invisible. Write a JavaScript to do border
invisible.
To make the frame border invisible, use frameborder='0' and style='border:none'.
Example:
<iframe src='page.html' width='300' height='200' frameborder='0'
style='border:none;'></iframe>
These methods help in testing, extracting, matching, and replacing string patterns using
regular expressions.
Example:
window.open('url', '_blank', 'left=200,top=100,width=300,height=200');
Examples:
(123)-4567-8901 => valid
123.4567.8901 => valid
Scrollable Menu: A menu that stays fixed in size but allows scrolling within its container
when there are too many items to fit at once.
b) Write JavaScript programs that create a scrolling text on the status line of a
window.
<script>
var msg = "Welcome to JavaScript! ";
var pos = 0;
function scrollMsg() {
window.status = msg.substring(pos) + msg.substring(0, pos);
pos = (pos + 1) % msg.length;
setTimeout(scrollMsg, 200);
}
scrollMsg();
</script>
a) Write a program that disables the right click of mouse button and displays
the message.
<script>
document.addEventListener('contextmenu', function(e) {
e.preventDefault();
alert('Right click button is disabled');
});
</script>
b) Develop the JavaScript program to create rotating banner ads with URL links.
<script>
var ads = [
{img: 'ad1.jpg', link: 'http://site1.com'},
{img: 'ad2.jpg', link: 'http://site2.com'},
{img: 'ad3.jpg', link: 'http://site3.com'}
];
var i = 0;
function rotateAds() {
var ad = ads[i];
document.getElementById('banner').innerHTML = `<a href='${ad.link}'><img src='$
{ad.img}'></a>`;
i = (i + 1) % ads.length;
setTimeout(rotateAds, 3000);
}
</script>
<div id='banner'></div>
<script>rotateAds();</script>
c) List ways of protecting your webpage and describe any one of them.
1. Disable right-click and keyboard shortcuts.
2. Minify and obfuscate JavaScript.
3. Use HTTPS to secure data.
4. Set up authentication and authorization.
This regex validates Indian mobile numbers starting with 6 to 9 and having a total of 10
digits.
c) Write JavaScript program that creates a scrolling text on the status line of a
window.
<script>
var msg = 'Scrolling Status Text - '; var pos = 0;
function scrollStatus() {
window.status = msg.substring(pos) + msg.substring(0, pos);
pos = (pos + 1) % msg.length;
setTimeout(scrollStatus, 200);
}
scrollStatus();
</script>
a) Develop a JavaScript Program to Create Rotating Banner Ads with URL Links.
<script>
var ads = [
{img: '1.jpg', url: 'http://link1.com'},
{img: '2.jpg', url: 'http://link2.com'},
{img: '3.jpg', url: 'http://link3.com'}
];
var index = 0;
function showBanner() {
var ad = ads[index];
document.getElementById('bannerAd').innerHTML = `<a href='${ad.url}'><img src='$
{ad.img}' width='300'></a>`;
index = (index + 1) % ads.length;
setTimeout(showBanner, 3000);
}
</script>
<div id='bannerAd'></div>
<script>showBanner();</script>