WT Unit V-Javascript-Long Answer Questions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

UNIT-V Question Bank Solutions

1. a) Explain variables in JavaScript with suitable examples?

Ans: Declaring a JavaScript Variable


Java script variables can be declared in 3 ways
var a;
let b;
const;
Var:
Creating a variable in JavaScript is called "declaring" a variable.
You declare a JavaScript variable with the var or the let keyword:
var carName;
After the declaration, the variable has no value (technically it is undefined).
To assign a value to the variable, use the equal sign:
Var carName = "Volvo";
Ex:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>Create a variable, assign a value to it, and display it:</p>
<p id="demo"></p>
<script>
let carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
</body>
</html>
Output:
JavaScript Variables
Create a variable, assign a value to it, and display it:
Volvo
Let:
The let keyword was introduced in ES6 (2015)
Variables defined with let must be Declared before use
Variables defined with let have Block Scope
Variables defined with let can be re declared.

let x = "John Doe";


let x = 0;

<!DOCTYPE html>
<html>
<body>
<h2>Redeclaring a Variable Using let</h2>
<p id="demo"></p>
<script>
let x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
Output:
Redeclaring a Variable Using let
10
const:
The const keyword was introduced in ES6 (2015)
Variables defined with const cannot be Redeclared
Variables defined with const cannot be Reassigned
Variables defined with const have Block Scope
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript const</h2>
<p id="demo"></p>
<script>
try {
const PI = 3.141592653589793;
PI = 3.14;
}
catch (err) {
document.getElementById("demo").innerHTML = err;
}
</script>
</body>
</html>
Output:
JavaScript const
TypeError: Assignment to constant variable.

b) Write a JavaScript program to display the Current Date.

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML Events</h2>
<p>Click the button to display the date.</p>
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
</body>
</html>
OUTPUT:
JavaScript HTML Events
Click the button to display the date.
The time is?
Sat Jun 24 2023 16:20:54 GMT+0530 (India Standard Time)

2 .a) Explain JavaScript with examples.

JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in
1997. JavaScript can be easy to code.

JavaScript is used to create client-side dynamic pages.

JavaScript is an object-based scripting language which is lightweight and cross-


platform.

JavaScript is not a compiled language, but it is a translated language. The JavaScript


Translator (embedded in the browser) is responsible for translating the JavaScript
code for the web browser.

In HTML, JavaScript code is inserted between <script> and </script> tags.

<script>
document.write("JavaScript is a simple language for learners");
</script>

JavaScript provides 3 places to put the JavaScript code:

1. within body tag,

2. within head tag

3. External JavaScript file.


JavaScript Can Change HTML Content

One of many JavaScript HTML methods is getElementById().

The example below "finds" an HTML element (with id="demo"), and changes the
element content (innerHTML) to "Hello JavaScript":

<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick='document.getElementById("demo").innerHTML =
"Hello JavaScript!"'>Click Me!</button>

</body>
</html>

OUTPUT:
2. b) Discuss how Javascript displays the data in various ways.

JavaScript can "display" data in different ways:

 Writing into an HTML element, using innerHTML.


 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log().

Using innerHTML

To access an HTML element, JavaScript can use

the document.getElementById(id) method.

The id attribute defines the HTML element. The innerHTML property defines
the HTML content:

Eg:

<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>

OUTPUT:

My First Web Page


My First Paragraph.
11
Using document.write():

document.write() method display the data. Never call document.write() after the
document has finished loading. It will overwrite the whole document
<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<p>Never call document.write after the document has finished loading.
It will overwrite the whole document.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>

OUTPUT:

My First Web Page


My first paragraph.

Never call document.write after the document has finished loading. It will
overwrite the whole document.

11

Using window.alert()
You can use an alert box to display data:
You can skip the window keyword. In JavaScript, the window object is the global
scope object. This means that variables, properties, and methods by default belong to
the window object. This also means that specifying the window keyword is optional:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5+6);
</script>
</body>
</html>

OUTPUT:

Using console.log()

For debugging purposes, you can call the console.log() method in the browser to
display data.

<!DOCTYPE html>
<html>
<body>
<h2>Activate Debugging</h2>
<p>F12 on your keyboard will activate debugging.</p>
<p>Then select "Console" in the debugger menu.</p>
<p>Then click Run again.</p>
<script>
console.log(5 + 6);
</script>
</body>
</html>

OUTPUT:

3. a) Explain the dialog boxes in Javascript with examples.

Ans: JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt
box.

Alert Box:

An alert box is often used if you want to make sure information comes through to the
user.

When an alert box pops up, the user will have to click "OK" to proceed.

Syntax:
window.alert("sometext");

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Alert</h2>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
</body>
</html>

OUTPUT:
Confirm Box:

A confirm box is often used if you want the user to verify or accept something.

When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed.

If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.

Syntax:

window.confirm("sometext");

Eg:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Confirm Box</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
OUTPUT:

Prompt Box

A prompt box is often used if you want the user to input a value before entering a
page.

When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
proceed after entering an input value.

If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the
box returns null.

Syntax:

window.prompt("sometext","defaultText");

Eg:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Prompt</h2>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
let text;
let person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person == "") {
text = "User cancelled the prompt.";
} else {
text = "Hello " + person + "! How are you today?";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
OUTPUT:

3.b)How functions are used in Javascript?

Ans: A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).

// Function to compute the product of p1 and p2


function myFunction(p1, p2) {
return p1 * p2;
}

A JavaScript function is defined with the function keyword, followed by a name,


followed by parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same rules
as variables).

The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3) {


// code to be executed
}
Function parameters are listed inside the parentheses () in the function definition.

Function arguments are the values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.

Function Invocation

The code inside the function will execute when "something" invokes (calls) the
function:

When an event occurs (when a user clicks a button)


When it is invoked (called) from JavaScript code
Automatically (self invoked)

Function Return

When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute the
code after the invoking statement.

Functions often compute a return value. The return value is "returned" back to the
"caller":

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<p>Call a function which performs a calculation and returns the result:</p>
<p id="demo"></p>
<script>
let x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
function myFunction(a, b) {
return a * b;
}
</script>
</body>
</html>

Output:
JavaScript Functions
Call a function which performs a calculation and returns the result:
12
4. Explain how parameters are passed to functions in JavaScript

Ans: A JavaScript function does not perform any checking on parameter values
(arguments).

Function Parameters and Arguments

function functionName(parameter1, parameter2, parameter3) {


// code to be executed
}Function parameters are the names listed in the function definition.

Function arguments are the real values passed to (and received by) the function.

Parameter Rules

JavaScript function definitions do not specify data types for parameters.

JavaScript functions do not perform type checking on the passed arguments.

JavaScript functions do not check the number of arguments received

Default Parameters

If a function is called with missing arguments (less than declared), the missing values
are set to undefined.

Sometimes this is acceptable, but sometimes it is better to assign a default value to the
parameter:

<!DOCTYPE html>
<html>
<body>
<p>Setting a default value to a function parameter.</p>
<p id="demo"></p>
<script>
function myFunction(x, y) {
if (y === undefined) {
y = 2;
}
return x * y;
}
document.getElementById("demo").innerHTML = myFunction(4);
</script>
</body>
</html>

Output:
Setting a default value to a function parameter.
8
Function Rest Parameter:

The rest parameter (...) allows a function to treat an indefinite number of arguments as
an array:

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>The Rest Parameter</h2>
<p>The rest parameter (...) allows a function to treat an indefinite number of
arguments as an array:</p>
<p id="demo"></p>
<script>
function sum(...args) {
let sum = 0;
for (let arg of args) sum += arg;
return sum;
}
let x = sum(4, 9, 16, 25, 29, 100, 66, 77);
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>

Output:
JavaScript Functions
The Rest Parameter
The rest parameter (...) allows a function to treat an indefinite number of arguments as
an array:
326

Arguments are Passed by Value


The parameters, in a function call, are the function's arguments.
JavaScript arguments are passed by value: The function only gets to know the values,
not the argument's locations.
If a function changes an argument's value, it does not change the parameter's original
value.
Changes to arguments are not visible (reflected) outside the function.

Objects are Passed by Reference


In JavaScript, object references are values.
Because of this, objects will behave like they are passed by reference:
If a function changes an object property, it changes the original value.
Changes to object properties are visible (reflected) outside the function.
5. Explain Javascript objects with example.
JavaScript Objects

A javaScript object is an entity having state and behavior (properties and method).

For example: car, pen, bike, chair, glass, keyboard, monitor etc.

JavaScript is an object-based language. Everything is an object in JavaScript.

JavaScript is template based not class based. Here, we don't create class to get the
object. But, we direct create objects.

Creating Objects in JavaScript

There are 3 ways to create objects.

By object literal
By creating instance of Object directly (using new keyword)
By using an object constructor (using new keyword)

1) JavaScript Object by object literal

The syntax of creating object using object literal is given below:

object={property1:value1,property2:value2.....propertyN:valueN}

As you can see, property and value is separated by : (colon).

<html>
<body>
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>

Output:
102 Shyam Kumar 40000
2) By creating instance of Object

The syntax of creating object directly is given below:

var objectname=new Object();

Here, new keyword is used to create object.

<html>
<body>
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>

Output:
101 Ravi Malik 50000

3) By using an Object constructor

Here, you need to create function with arguments. Each argument value can be
assigned in the current object by using this keyword.

<html>
<body>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);


</script>
</body>
</html>
Output:
103 Vimal Jaiswal 30000
6. Explain about JavaScript Events.

JavaScript's interaction with HTML is handled through events that occur when the
user or the browser manipulates a page.
 When the page loads, it is called an event. When the user clicks a button, that
click too is an event. Other examples include events like pressing any key,
closing a window, resizing a window, etc.
 Developers can use these events to execute JavaScript coded responses, which
cause buttons to close windows, messages to be displayed to users, data to be
validated, and virtually any other type of response imaginable.
 Events are a part of the Document Object Model (DOM) Level 3 and every
HTML element contains a set of events which can trigger JavaScript Code.
onclick Event Type:
This is the most frequently used event type which occurs when a user clicks the left
button of his mouse. You can put your validation, warning etc., against this event type.
<html>
<head>
<script type = "text/javascript">
function sayHello() {
alert("Hello World")
}

</script>
</head>

<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>

onsubmit Event Type


onsubmit is an event that occurs when you try to submit a form. You can put your
form validation against this event type.
Example:
<!DOCTYPE html>
<html>
<body>
<p>When you submit the form, a function is triggered which alerts some text.</p>

<form action="/action_page.php" onsubmit="myFunction()">


Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function myFunction() {
alert("The form was submitted");
}
</script>
</body>
</html>

onmouseover and onmouseout


These two event types will help you create nice effects with images or even with text
as well. The onmouseover event triggers when you bring your mouse over any
element and the onmouseout triggers when you move your mouse out from that
element.
<!DOCTYPE html>
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The onmouseover Event</h2>
<img onmouseover="bigImg(this)" onmouseout="normalImg(this)" border="0"
src="smiley.gif" alt="Smiley" width="32" height="32">
<p>The function bigImg() is triggered when the user moves the mouse pointer over
the image.</p>
<p>The function normalImg() is triggered when the mouse pointer is moved out of
the image.</p>
<script>
function bigImg(x) {
x.style.height = "64px";
x.style.width = "64px";
}

function normalImg(x) {
x.style.height = "32px";
x.style.width = "32px";
}
</script>
</body>
</html>
7. Discuss DOM with suitable examples.

The Document Object Model (DOM) is a programming


interface for HTML(HyperText Markup Language) and XML(Extensible markup
language) documents. It defines the logical structure of documents and the way a
document is accessed and manipulated.

Why DOM is required?


HTML is used to structure the web pages and Javascript is used to add behavior to
our web pages. When an HTML file is loaded into the browser, the javascript can
not understand the HTML document directly. So, a corresponding document is
created(DOM). DOM is basically the representation of the same HTML document
but in a different format with the use of objects. Javascript interprets DOM easily i.e
javascript can not understand the tags(<h1>H</h1>) in HTML document but can
understand object h1 in DOM. Now, Javascript can access each of the objects (h1, p,
etc) by using different functions.
Structure of DOM:
DOM can be thought of as a Tree or Forest(more than one tree). The term structure
model is sometimes used to describe the tree-like representation of a
document. Each branch of the tree ends in a node, and each node contains
objects .Event listeners can be added to nodes and triggered on an occurrence of a
given event. One important property of DOM structure models is structural
isomorphism: if any two DOM implementations are used to create a representation
of the same document, they will create the same structure model, with precisely the
same objects and relationships.
Why called an Object Model?
Documents are modeled using objects, and the model includes not only the structure
of a document but also the behavior of a document and the objects of which it is
composed like tag elements with attributes in HTML.
Properties of DOM: Let’s see the properties of the document object that can be
accessed and modified by the document object.
Representation of the DOM
Window Object: Window Object is object of the browser which is always at top of
the hierarchy. It is like an API that is used to set and access all the properties and
methods of the browser. It is automatically created by the browser.
Document object: When an HTML document is loaded into a window, it becomes a
document object. The ‘document’ object has various properties that refer to other
objects which allow access to and modification of the content of the web page. If
there is a need to access any element in an HTML page, we always start with
accessing the ‘document’ object. Document object is property of window object.
Form Object: It is represented by form tags.
Link Object: It is represented by link tags.
Anchor Object: It is represented by a href tags.
Form Control Elements:: Form can have many control elements such as text fields,
buttons, radio buttons, checkboxes, etc.
Methods of Document Object:
write(“string”): Writes the given string on the document.
getElementById(): returns the element having the given id value.
getElementsByName(): returns all the elements having the given name value.
getElementsByTagName(): returns all the elements having the given tag name.
getElementsByClassName(): returns all the elements having the given class name.
<!DOCTYPE html>
<html>
<body>
<h2>WEB Technologies</h2>
<!-- Finding the HTML Elements by their Id in DOM -->
<p id="intro">A Computer Science portal for geeks.</p>
<p>This example illustrates the <b>getElementById</b> method.</p>
<p id="demo"></p>
<script>
const element = document.getElementById("intro");
document.getElementById("demo").innerHTML =
"Web Technology introduction is: " + element.innerHTML;
</script>
</body>
</html>

8.a.) Explain form validation in Javascript.

JavaScript Form Validation

HTML form validation can be done by JavaScript.

If a form field (fname) is empty, this function alerts a message, and returns false, to
prevent the form from being submitted:

function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
else{
alert(“Your name is”+x);
}
}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>
<form name="myForm" action="/action_page.php" onsubmit="return
validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>

8.b) Write a Javascript program to validate a phone number.


<!DOCTYPE html>
<html>
<body>
<form id="myform">
<label for="phone">Phone Number:</label>
<input type="text" id="phoneNo" name="phone" />
<br />
<br />
<button type="submit">Submit</button>
<br />
<br />
<div id="result"></div>
</form>
<script>
function validateNumber(input) {
var re = /^(\d{3})[- ]?(\d{3})[- ]?(\d{4})$/
return re.test(input)
}

function validateForm(event) {
var number = document.getElementById('phoneNo').value
if (!validateNumber(number)) {
alert('Please enter a valid number')
const ele = document.getElementById('result')
ele.innerHTML = 'Validation Failed'
ele.style.color = 'red'
} else {
const ele = document.getElementById('result')
ele.innerHTML = 'Validation Successful'
ele.style.color = 'green'
}
event.preventDefault()
}

document.getElementById('myform').addEventListener('submit', validateForm)
</script>
</body>
</html>

9. a)Write a Javascript program to validate login page.


<!DOCTYPE html>
<html>
<head>
<title>LOGIN FORM VALIDATION</title>
</head>
<body>
<h2>LOGIN FORM</h2>
<form method="post" onsubmit="validation()">
<input type="text" id="uname" placeholder="Enter User name"><br><br>
<input type="text" id="pwd" placeholder="Enter Password"><br><br>
<input type="submit" value="Login">
</form>
<script>
function validation(){
var un=document.getElementById('uname').value;
var ps=document.getElementById('pwd').value;
if (un == "john" && ps == "john@123"){
window.alert("Login Successful");
}
else{
window.alert("Login Failed");
}
}
</script>
</body>
</html>

9. b)Write a JavaScript Program to generate the Fibonacci series between 1 to 50.

<html>
<body>
<script>
const number = parseInt(prompt('Enter a positive number: '));
let n1 = 0, n2 = 1, nextTerm;
document.write('Fibonacci Series:'+"<br>");
document.write(n1+"<br>"); // print 0
document.write(n2+"<br>"); // print 1
nextTerm = n1 + n2;
while (nextTerm <= number) {
// print the next term
document.write(nextTerm+"<br>");
n1 = n2;
n2 = nextTerm;
nextTerm = n1 + n2;
}
</script>
</body>
</html>

OUTPUT:
Enter a positive number: 50
Fibonacci Series:
0
1
1
2
3
5
8
13
21
34
10. a)Write a Javascript program to validate an email.

JavaScript email validation:


Presence of @ and . character
Presence of at least one character before and after the @.
Presence of at least two characters after . (dot).
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="/action_page.php" onsubmit="return
validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>
</html>

10.b) Discuss about AJAX

AJAX = Asynchronous JavaScript And XML.


AJAX is not a programming language.
AJAX just uses a combination of:
 A browser built-in XMLHttpRequest object (to request data from a web
server)
 JavaScript and HTML DOM (to display or use the data)
AJAX allows web pages to be updated asynchronously by exchanging data with a
web server behind the scenes. This means that it is possible to update parts of a web
page, without reloading the whole page.

1. An event occurs in a web page (the page is loaded, a button is clicked)


2. An XMLHttpRequest object is created by JavaScript
3. The XMLHttpRequest object sends a request to a web server
4. The server processes the request
5. The server sends a response back to the web page
6. The response is read by JavaScript
7. Proper action (like page update) is performed by JavaScript

Modern Browsers (Fetch API)


Modern Browsers can use Fetch API instead of the XMLHttpRequest Object.
The Fetch API interface allows web browser to make HTTP requests to web servers.
If you use the XMLHttpRequest Object, Fetch can do the same in a simpler way.

AJAX - The XMLHttpRequest Object

The keystone of AJAX is the XMLHttpRequest object.

1. Create an XMLHttpRequest object


2. Define a callback function
3. Open the XMLHttpRequest object
4. Send a Request to a server
The XMLHttpRequest Object

All modern browsers support the XMLHttpRequest object.

The XMLHttpRequest object can be used to exchange data with a web server behind
the scenes. This means that it is possible to update parts of a web page, without
reloading the whole page.

You might also like