WT Unit V-Javascript-Long Answer Questions
WT Unit V-Javascript-Long Answer Questions
WT Unit V-Javascript-Long Answer Questions
<!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.
<!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)
JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in
1997. JavaScript can be easy to code.
<script>
document.write("JavaScript is a simple language for learners");
</script>
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.
Using innerHTML
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:
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:
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:
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:
Function names can contain letters, digits, underscores, and dollar signs (same rules
as variables).
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:
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 arguments are the real values passed to (and received by) the function.
Parameter Rules
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
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 template based not class based. Here, we don't create class to get the
object. But, we direct create objects.
By object literal
By creating instance of Object directly (using new keyword)
By using an object constructor (using new keyword)
object={property1:value1,property2:value2.....propertyN:valueN}
<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
<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
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);
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>
function normalImg(x) {
x.style.height = "32px";
x.style.width = "32px";
}
</script>
</body>
</html>
7. Discuss DOM with suitable examples.
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>
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>
<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.
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.