Important Question
Important Question
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
b) Assignment Operators
Operator Example Same As
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
c) Comparison Operators
Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
d) Logical Operators
Operator Description
&& logical and
|| logical or
! logical not
5. Explain function definition.
Ans :
JavaScript functions are defined with the function keyword.
You can use a function declaration or a function expression.
Syntax:
function functionName(parameters)
{
// code to be executed
}
E.g. : function myFunction(a, b)
{
return a * b;
}
i) If….Else statement - If….Else statement if you have to check two conditions and execute a
different set of codes.
e.g. : if (condition)
{
lines of code to be executed if the condition is true
}
else
{
lines of code to be executed if the condition is false
}
ii) if…else if statement - If….Else If….Else statement if you want to check more than two conditions.
e.g. : if (condition1)
{
lines of code to be executed if condition1 is true
}
else if(condition2)
{
lines of code to be executed if condition2 is true
}
else
{
lines of code to be executed if condition1 is false and condition2 is false
}
2. Setter :
const person = {
firstName: "John",
lastName: "Doe",
language: "",
set lang(lang) {
this.language = lang;
}
};
// Set an object property using a setter:
person.lang = "en";
// Display data from the object:
document.getElementById("demo").innerHTML = person.language;
9. Write a JavaScript program to implement arithmetic operators.
Ans : <html>
<body>
<h1>JavaScript Arithmetic</h1>
<h2>Operator Precedence</h2>
<p>Multiplication has precedence over addition.</p>
<p>But parenthesis has precedence over multiplication.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = (100 + 50) * 3;
</script> </body> </html>
ii) join() :
The join() method returns an array as a string.
The join() method does not change the original array.
Any separator can be specified. The default is comma (,).
Syntax : array.join(separator)
3. What is (i) shift(), (ii) unshift(), (iii) Pop() and (iv) Push()
Ans :
(i). shift() :
The shift() method removes the first item of an array.
The shift() method changes the original array.
The shift() method returns the shifted element.
Syntax : array.shift()
e.g. : <script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();
document.getElementById("demo").innerHTML = fruits;
</script>
O/P : Orange,Apple,Mango
(ii) unshift() :
The unshift() method adds new elements to the beginning of an array.
The unshift() method overwrites the original array.
Syntax : array.unshift(item1, item2, ..., itemX)
e.g. : <script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon", "Pineapple");
document.getElementById("demo").innerHTML = fruits;
</script>
O/P : Lemon,Pineapple,Banana,Orange,Apple,Mango
(iii) pop() :
The pop() method removes (pops) the last element of an array.
The pop() method changes the original array.
The pop() method returns the removed element.
Syntax : array.pop()
e.g. : <script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let removed = fruits.pop();
document.getElementById("demo").innerHTML = removed;
</script>
O/P : Mango
(iv) Push() :
The push() method adds new items to the end of an array.
The push() method changes the length of the array.
The push() method returns the new length.
Syntax : array.push(item1, item2, ..., itemX)
e.g. : <script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi", "Lemon");
document.getElementById("demo").innerHTML = fruits;
</script>
O/P : Banana,Orange,Apple,Mango,Kiwi,Lemon
e.g.: <script>
let text = "HELLO WORLD";
let code = text.charCodeAt(0);
document.getElementById("demo").innerHTML = code;
</script>
The index of the last character is string length – 1 get the Unicode of the last character
e.g.: <script>
let text = "HELLO WORLD";
let code = text.charCodeAt(text.length-1);
document.getElementById("demo").innerHTML = code;
</script>
2. fromCharCode() :
The String.fromCharCode() method converts Unicode values to characters.
The String.fromCharCode() is a static method of the String object.
Syntax : String.fromCharCode(n1, n2, ..., nX)
e.g.: <script>
let text = String.fromCharCode(65);
document.getElementById("demo").innerHTML = text;
</script>
Unit III : Form and Event Handling
1. Explain building blocks of form.
Ans : There are few differences between a straight HTML form and a JavaScript-enhanced form.
The main one being that a JavaScript form relies on one or more event handlers, such as onClick or
onSubmit. These invoke a JavaScript action when the user does something in the form, like clicking a button.
The event handlers, which are placed with the rest of the attributes in the HTML form tags, are invisible to
a browser that doesn’t support JavaScript.
An HTML document consist of its basic building blocks which are:
o Tags: An HTML tag surrounds the content and apply meaning to it. It is written between < and > brackets.
o Attribute: An attribute in HTML provides extra information about the element, and it is applied within the
start tag. An HTML attribute contains two fields: name & value.
o Elements: An HTML element is an individual component of an HTML file. In an HTML file, everything
written within tags are termed as HTML elements.
2. Explain form tag with all its attributes.
Ans : The <form> tag is used to create an HTML form for user input.
Attributes :
Event Description
onclick The event occurs when the user clicks on an element
oncontextmenu The event occurs when the user right-clicks on an element to open a context menu
ondblclick The event occurs when the user double-clicks on an element
onmousedown The event occurs when the user presses a mouse button over an element
onmouseenter The event occurs when the pointer is moved onto an element
onmouseleave The event occurs when the pointer is moved out of an element
onmousemove The event occurs when the pointer is moving while it is over an element
onmouseout The event occurs when a user moves the mouse pointer out of an element, or out of one
of its children
onmouseover The event occurs when the pointer is moved onto an element, or onto one of its children
onmouseup The event occurs when a user releases a mouse button over an element
10. Explain various keyboard events with example.
Ans : These event types belongs to the KeyboardEvent Object:
Event Description
onkeydown The event occurs when the user is pressing a key
2. setInterval(function, milliseconds) : Same as setTimeout(), but repeats the execution of the function
continuously.
Syntax : window.setInterval(function, milliseconds);
e.g. : <html>
<body>
<p id="demo"></p>
<script>
setInterval(myTimer, 1000);
function myTimer() {
const d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
</body>
</html>
3. How to create cookie. Explain with an example.
Ans :
The simplest way to create a cookie is to assign a string value to the document.cookie object.
Syntax :- document.cookie = "key1 = value1;key2 = value2;expires = date";
Here the expires attribute is optional. If you provide this attribute with a valid date or time, then the
cookie will expire on a given date or time and thereafter, the cookies' value will not be accessible.
e.g. : <html>
<body>
<input type="button" value="setCookie" onclick="setCookie()">
<input type="button" value="getCookie" onclick="getCookie()">
<script type=”text/javascript”>
function setCookie()
{
document.cookie="username=Gramin Poly";
}
function getCookie()
{
if(document.cookie.length!=0)
{
var array=document.cookie.split("=");
alert("Name="+array[0]+" "+"Value="+array[1]);
}
else
{
alert("Cookie not available");
}
}
</script>
</body>
</html>
4. How to delete a cookie. Explain with an example.
Ans :
Deleting a cookie is very simple.
You don't have to specify a cookie value when you delete a cookie.
Just set the expires parameter to a past date:
Syntax : document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
e.g. : <html>
<body>
<input type="button" value="Set Cookie" onclick="setCookie()">
<input type="button" value="Get Cookie" onclick="getCookie()">
<input type="button" value="Delete Cookie1" onclick="delCookie1()">
<input type="button" value="Delete Cookie2" onclick="delCookie2()">
<input type="button" value="Delete Cookie3" onclick="delCookie3()">
<script type="text/javascript">
function setCookie()
{
document.cookie="name=Gramin Poly";
}
function getCookie()
{
if(document.cookie.length!=0)
{
alert(document.cookie);
}
else
{
alert("Cookie not avaliable");
}
}
function delCookie1()
{
document.cookie="name=Gramin Poly; expires=Wednesday, August 07,2019 10:00 AM";
alert("Expiry set");
}
function delCookie2()
{
document.cookie="name=Gramin Poly;max-age=0";
alert("Max Age Set to 0");
}
function delCookie3()
{
document.cookie="name=";
alert("Directly deleted cookie");
}
</script>
</body>
</html>
5. How to set expiration date to a cookie. Explain with an example.
Ans :
Cookies are usually temporary, so you might want to set a precise expiry date.
Use Expires and set a fixed expiration date.
The date uses the HTTP date format : <day-name>, <day> <month> <year>
<hour>:<minute>:<second> GMT.
e.g. : const setCookieExpiry = new Date(2020, 8, 17); document.cookie = “name=Gramin; expires =”+
setCookieExpiry.toUTCString() + ';';
Use toUTCString() for converting Date() method to string.
4. What is Frame?
Ans :
Frames are used to divide the web browser window into multiple sections where each section can be
loaded separately.
A frameset tag is the collection of frames in the browser window.
e.g. : <html>
<frameset cols = "30%,40%,30%" frameborder="1">
<frame name = "top" src = "D:\Example\arrayByConstructor.html" />
<frame name = "main" src = "D:\Example\checkBox.html" />
<frame name = "bottom" src = "D:\Example\demo1.html" />
</frameset>
</html>
5. What is rollover?
Ans :
Rollover is a JavaScript technique used by Web developers to produce an effect in which the
appearance of a graphical image changes when the user rolls the mouse pointer over it.
Rollover also refers to a button on a Web page that allows interactivity between the user and the
Web page.
Rollover can be accomplished using text, buttons or images, which can be made to appear when the
mouse is rolled over an image.
The user needs two images/buttons to perform rollover action.
The keyword that is used to create rollover is the event.
e.g. : <html>
<body>
<img src="D:\Tulips.jpg" boarder="0px" width="300px" height="200px"
onmouseover="this.src='D:\Desert.jpg';" onmouseout="this.src='D:\Penguins.jpg';" />
</body>
</html>
6. What is text rollover?
Ans :
The keyword that is used to create rollover is the event.
For example, we want to create a rollover text that appears in a text area.
The text “What is rollover?” appears when the user place his or her mouse over the text area and the
rollover text changes to “Rollover means a webpage changes when the user moves his or her mouse
over an object on the page” when the user moves his or her mouse away from the text area.
e.g. : <html>
<body>
<textarea rows="2" cols="50" name=rollovertext" onmouseover="this.value='What is text rollover?';"
onmouseout="this.value='Rollover means changes when the user moves the mouse on the
page';"></textarea>
</body>
</html>
7. Explain the language of regular expression.
Ans : When we create a set of word by using the different patterns of the regular expression in JavaScript it is
known as language of regular expression. Following are some of the patterns available:
1. Brackets: Brackets ([]) : have a special meaning when used in the context of regular expressions. They are
used to find a range of characters.
• [...] - Any one character between the brackets.
• [^...] - Any one character not between the brackets.
• [0-9] - It matches any decimal digit from 0 through 9.
• [a-z] It matches any character from lowercase a through lowercase z.
• [A-Z] It matches any character from uppercase A through uppercase Z.
• [a-Z] It matches any character from lowercase a through uppercase Z.
2. Qualifiers : The frequency or position of bracketed character sequences and single characters can be denoted
by a special character. Each special character has a specific connotation. The +, *, ?, and $ flags all follow a
character sequence
• p+ : It matches any string containing one or more p's
• p* : It matches any string containing zero or more p's
• p? : It matches any string containing at most one p
• p$ : It matches any string with p at the end of it.
3. Metacharacters : A metacharacter is simply an alphabetical character preceded by a backslash that acts to give
the combination a special meaning.
1. . - a single character
2. \s - a whitespace character (space, tab, newline)
3. \S - non-whitespace character
4. \d - a digit (0-9)
5. \D - a non-digit
6. \w - a word character (a-z, A-Z, 0-9, _)
7. \W - a non-word character
8. [\b] - a literal backspace (special case).
9. [aeiou] - matches a single character in the given set
10. [^aeiou] - matches a single character outside the given set
11. \t - a tab character
12. \n - a newline character
13. \v - a vertical tab
8. How to match punctuations and symbols? Explain with an example.
Ans :
Regular expression patterns include the use of letters, digits, punctuation marks, etc., plus a set of
special regular expression characters.
The characters that are given special meaning within a regular expression, are: . * ? + [ ] ( ) { } ^ $ |
\. You will need to backslash these characters whenever you want to use them literally. For example,
if you want to match ".", you'd have to write \..
All other characters automatically assume their literal meanings.
e.g. : <html>
<input type="text" name="tx1">
<input type="submit" value="check" onclick="check()">
<script type="text/javascript">
function check()
{
var email=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-z])+$/;
if(tx1.value.match(email))
{
alert("valid mail id");
}
else
{
alert("invalid mail id");
}
}
</script>
</html>
9. How to match words? Explain with an example.
Ans : match() is an inbuilt function in JavaScript which is used to search a string for a match against a any regular
expression and if the match will found then this will return the match as an array.
e.g. : <html>
<input type="text" id="tx1"><br>
<input type="button" value="click" onclick="check()">
<script type="text/javascript">
function check()
{ var str=tx1.value;
var chkPtrn=/poly/i;
if(str.match(chkPtrn))
{ alert("String contains the given pattern");
}
else
{ alert("String does not contains the given pattern");
}
} </script> </html>
10. How to create frames also explain the attributes of Frameset and Frame tag.
Ans : To use frames on a page we use tag instead of tag. The tag defines how to divide the window into frames.
Attributes of Frameset tag:
Attributes of Frame tag :
11. How to set the border of the frame invisible? Explain with an example.
Ans : Frameborder attribute of frameset tag is used to specify whether the three dimensional border should be
displayed between the frames or not for this use two values 0 and 1, where 0 defines for no border and value 1
signifies for yes there will be border.
e.g. : <html>
<frameset cols = "30%,40%,30%" >
<frame name = "top" frameborder="0"/>
<frame name = "main" frameborder="0"/>
<frame name = "bottom" frameborder="0"/>
</frameset>
</html>
12. How to call a child window? Explain with an example.
Ans :
We need to interact with other frames with JavaScript function.
Every frame is parent or child of parent. Every frame has own id and frame name which differentiate
one frame to other frames.
We denote frame as child or parent. This makes it easy to access other frame from frame to frame.
e.g. : Example:- (Parent Frame)
<html>
<frameset cols="25%,75%">
<frame src="d:\child1.html" name="frame1"/>
<frame src="d:\child2.html" name="frame2"/>
</frameset>
</html>
Example: - (Child Frame1)
<html>
<body>
<input type="button" value="click" onclick="parent.frame2.disp()"/>
</body>
</html>
Example: - (Child Frame2)
<html>
<script type="text/javascript">
function disp()
{
document.write("This function is called from Frame1");
}
</script>
</html>
13. How to change the content and focus of child window? Explain with an example.
Ans : The content and focus of child window can be changed from another child window. This can be done by
changing the source file for the particular by using JavaScript.
e.g. : (Parent Frame)
<html>
<frameset cols="25%,75%">
<frame src="d:\child1.html" name="frame1"/>
<frame src="d:\child2.html" name="frame2"/>
</frameset>
</html>
(Child Frame1)
<html>
<body>
<input type="button" value="click" onclick="disp()"/>
<script type="text/javascript">
function disp()
{ parent.frame2.location.href="d:\\ child3.html";
}
</script> </body> </html>
(Child Frame2)
<html>
<h1>Frame2</h2>
</html>
(Child Frame3)
<html>
<h1>Content & focus changed from child2 to child3</h2>
</html>
14. How to access the elements of child window from another child window? Explain with an example.
Ans : One can change access the elements of one child window from another by getting the ID of the element used.
e.g : (Parent Frame)
<html>
<frameset cols="25%,75%">
<frame src="d:\child1.html" name="frame1"/>
<frame src="d:\child2.html" name="frame2"/>
</frameset> </html>
(Child Frame1)
<html>
<body>
<input type="button" value="click" onclick="disp()"/>
<script type="text/javascript">
function disp()
{
parent.frame2.document.getElementById("p1").innerHTML="Element is accessed by frame 2";
}
</script> </body> </html>
(Child Frame2)
<html>
<h1>Frame2</h2>
<p id="p1"> Frame 2 contents</p>
</html>
15. How to perform multiple actions by using rollover? Explain with example.
Ans : One can perform multiple actions on the rollover event of mouse like displaying image and displaying text
for that image.
e.g. : <html>
<body>
<a href="" onmouseover="disp()"> Tulip</a><br><br>
<img src="" name="im1" width="200" height="200"><br><br>
<p id="p1">Description of Flower</p>
<script type="text/javascript">
function disp()
{
document.im1.src="D:\Tulips.jpg";
document.getElementById("p1").innerHTML="This is Tulip Flower";
}
</script>
</body> </html>
Unit VI Menus Navigation and Web Page Protection
1. What is slide show?
Ans :
A web slideshow is a sequence of images or text that consists of showing one element of the sequence in a
certain time interval.
In the slideshow JavaScript code, we create an array MySlides to store the banner images using the
following statement:
MySlides=new Array(‘banner1.jpg’,’banner2.jpg’,’banner3.jpg’,’banner4.jpg’)
2. What is menu in JavaScript? List and explain various types of menus available.
Ans :
A menu is a set of options presented to the user of a computer application to help them find
information or execute a function.
Types Of Menus
a. Creating Pull down Menu : Drop down menus in a website are an important element when it comes to
affective navigation of Webpages.
b. Dynamically changing the Menu: The item of the menu can be changed dynamically depending upon action
takes place.
c. Validating Menu selection: Validation refers to check whether the information if filled correctly. In this case
if the user doesn’t select any option then it prompt user to select appropriate option and proceed
d. Chain Select Menu : Chain select menu is a type of dynamic menu in which there is more than one select
menu present.
e. Tab Menu: Tab menu contain one or more tab-head like a button. Each tab contains separate content to
display.
f. Popup Menu : Popup menu is nothing but a hover able dropdown menu. The drop down menu display the
sub menu on mouse over is known as popup menu.
g. Sliding Menu : Sliding menu is not present on the screen. When we want it we should click on the button or
menu icon then it will slide in the screen
h. Highlighted Menu : Sometimes there is a need to highlight a particular menu item. You can highlight a
menu by adding a different background color, text color etc.
i. Context Menu: When the user click right mouse button on the webpage then the context menu is displayed
and the position of menu is depend on the location where the mouse is clicked.
j. Scrollable Menu : The menu in which items can be scrolled to display limited item on screen is called
scrollable menu.
k. Side Bar Menu : In side bar menu, the sub menu of a menu item will be displayed on right side of the menu.
When we click on the menu item, the sub menu of that menu will be displayed on right side of the menu.
2. Watch out for SQL injection : SQL injection attacks are when an attacker uses a web form field or URL
parameter to gain access to or manipulate your database.
3. Protect against XSS attacks : Cross-site scripting (XSS) attacks inject malicious JavaScript into your pages,
which then runs in the browsers of your users, and can change page content, or steal information to send
back to the attacker.
4. Beware of error messages : Be careful with how much information you give away in your error messages.
Provide only minimal errors to your users, to ensure they don't leak secrets present on your server (e.g. API
keys or database passwords).
5. Validate on both sides : Validation should always be done both on the browser and server side.
6. Check your passwords : It is crucial to use strong passwords to your server and website admin area, but
equally also important to insist on good password practices for your users to protect the security of their
accounts.
7. Avoid file uploads : The risk is that any file uploaded, however innocent it may look, could contain a script
that when executed on your server, completely opens up your website.
8. Use HTTPS : HTTPS is a protocol used to provide security over the Internet.
9. Get website security tools : The most effective way of doing this is via the use of some website security
tools, often referred to as penetration testing or pen testing for short.
10. Disable right click: - Source code of the webpage of some websites can be viewed by right clicking and
click on view source option. By disabling the right click one can hide the source code from the other users.
Program
Section
1. Write a JavaScript program to implement arithmetic operators.
Ans : <html>
<body>
<h1>JavaScript Arithmetic</h1>
<p id="demo"></p>
<script>
let a = 3;
let x = (100 + 50) * a;
document.getElementById("demo").innerHTML = x;
</script> </body> </html>
2. Write a JavaScript program to demonstrate if…else if statement.
Ans : <html>
<body>
<h2>JavaScript if .. else</h2>
<p id="demo"></p>
<script>
const time = new Date().getHours();
let greeting;
if (time < 10)
{
greeting = "Good morning";
}
else if (time < 20)
{
greeting = "Good day";
}
else
{
greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
</script> </body> </html>
3. Write a JavaScript program to demonstrate Switch case statement.
Ans : <html>
<body>
<h2>JavaScript switch</h2>
<p id="demo"></p>
<script>
let day;
switch (new Date().getDay())
{
case 0: day = "Sunday";
break;
case 1: day = "Monday";
break;
case 2: day = "Tuesday";
break;
case 3: day = "Wednesday";
break;
case 4: day = "Thursday";
break;
case 5: day = "Friday";
break;
case 6: day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script> </body> </html>
4. Write a JavaScript program to demonstrate for loop statement.
Ans: <html>
<body>
<h2>JavaScript For Loop</h2>
<p id="demo"></p>
<script>
let text = "";
for (let i = 0; i < 5; i++)
{
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
5. Write a JavaScript program to demonstrate while loop statement.
Ans : <html>
<body>
<h2>JavaScript While Loop</h2>
<p id="demo"></p>
<script>
let text = "";
let i = 0;
while (i < 10)
{
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
6. Write a JavaScript program to create and initialize array elements.
Ans : <html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>
7. Write a JavaScript program to demonstrate shift(), unshift(), push(),pop(), splice().
Ans : a. The unshift() Method
<html>
<body>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon", "Pineapple");
document.getElementById("demo").innerHTML = fruits;
</script> </body> </html>
/* Slideshow container */
.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}
/* Caption text */
.text {
color: #f2f2f2;
font-size: 15px;
padding: 8px 12px;
position: absolute;
bottom: 8px;
width: 100%;
text-align: center;
}
/* The dots/bullets/indicators */
.dot {
cursor: pointer;
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.active, .dot:hover {
background-color: #717171;
}
/* Fading animation */
. fade {
animation-name: fade;
animation-duration: 1.5s;
}
@keyframes fade {
from {opacity: .4}
to {opacity: 1}
}