Experiment No: 4
Date of Performance:
Date of Submission:
Aim:
JavaScript: Variables, Operators, Conditions, Loops, Functions, Events, Classes and Objects,
Error handling, Validations, Arrays, String, Date
Theory:
● JavaScript is the world's most popular programming language.
● JavaScript is the programming language of the Web.
● JavaScript is easy to learn.
● JavaScript accepts both double and single quotes
JavaScript is one of the 3 languages all web developers must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages
First Program on JavaScript:
<!DOCTYPE html>
<html>
<head>
<style>
body {
text-align: center;
font-family: Arial, sans-serif;
background-color: #f4f4f4;
}
button {
padding: 10px 20px;
font-size: 16px;
margin: 10px;
cursor: pointer;
border: none;
border-radius: 5px;
}
#status {
font-weight: bold;
margin-top: 10px;
}
</style>
</head>
<body>
<h2>My JavaScript Light Experiment</h2>
<p>Now the light tells you its status, and you can toggle it with one button!</p>
<img id="myImage" src="https://www.w3schools.com/js/pic_bulboff.gif" style="width:150px">
<p id="status">The light is OFF</p>
<button id="toggleBtn">Turn ON the light</button>
<script>
let isOn = false;
document.getElementById("toggleBtn").addEventListener("click", function() {
const bulb = document.getElementById("myImage");
const status = document.getElementById("status");
if (!isOn) {
bulb.src = "https://www.w3schools.com/js/pic_bulbon.gif";
status.textContent = "The light is ON";
this.textContent = "Turn OFF the light";
document.body.style.backgroundColor = "#fff7cc";
} else {
bulb.src = "https://www.w3schools.com/js/pic_bulboff.gif";
status.textContent = "The light is OFF";
this.textContent = "Turn ON the light";
document.body.style.backgroundColor = "#f4f4f4";
}
isOn = !isOn;
});
</script>
</body>
</html>
Output:
Program on Changing the style of an HTML element attribute:
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<button type="button" onclick="changeStyle()">Click Me!</button>
<script>
function changeStyle() {
let element = document.getElementById("demo");
element.style.fontSize = "35px";
element.style.fontWeight = "bold"; // added: make text bold
}
</script>
</body>
</html>
Output:
Before Button Click
After Button Click
JavaScript Conditional Statements (if..else..else if..switch)
● Use if to specify a block of code to be executed, if a specified condition is true
● Use else to specify a block of code to be executed, if the same condition is false
● Use else if to specify a new condition to test, if the first condition is false
● Use switch to specify many alternative blocks of code to be executed
Program on if .. else:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if .. else</h2>
<p>A time-based greeting:</p>
<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 + " (Current hour: " + time + ")";
</script>
</body>
</html>
Output:
Program on switch:
<!DOCTYPE html>
<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";
}
let fullDate = new Date().toDateString();
document.getElementById("demo").innerHTML = "Today is " + day + " (" + fullDate + ")";
</script>
</body>
</html>
Output:
Program on for:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Loop</h2>
<p id="demo"></p>
<script>
const fruits = ["Apple", "Banana", "Cherry", "Mango"];
let i = 0;
let len = fruits.length;
let text = "";
for (; i < len; ) {
text += (i + 1) + ". " + fruits[i] + "<br>";
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Output:
Program on for/in:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For In Loop</h2>
<p>The for in statement loops through the properties of an object:</p>
<p id="demo"></p>
<script>
const book = {
title: "The Great Gatsby",
author: "F. Scott Fitzgerald",
year: 1925
};
let txt = "";
for (let prop in book) {
txt += prop + ": " + book[prop] + "<br>";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
Output:
Program on for/of:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Of Loop</h2>
<p>The for of statement loops through the values of any iterable object:</p>
<p id="demo"></p>
<script>
const animals = ["Cat", "Dog", "Elephant"];
let text = "";
let count = 1;
for (let x of animals) {
text += count + ". " + x + "<br>"; // Added numbering
count++;
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Output:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Of Loop</h2>
<p>The for of statement loops through the values of an iterable object.</p>
<p id="demo"></p>
<script>
let language = "HELLO";
let text = "";
for (let x of language) {
text += x + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Output:
JS Function to find sum of n natural numbers:
<html>
<head>
<script>
function findSum(n)
{
let result = 0;
for(let i = 1; i <= n; i++) {result = result + i; }
document.getElementById("demo").innerHTML = result
}
</script>
</head>
<body>
<button onclick="findSum(10)">Click Me</button>
<p id="demo"></p>
</body>
</html>
Output:
Program on Click Event:
<html>
<head> JavaScript Events </head>
<body>
<script type="text/javascript">
🎉
function clickevent() {
document.write("You found the secret message! ");
}
</script>
<form>
<input type="button" onclick="clickevent()" value="Click me for a surprise!"/>
</form>
</body>
</html>
Output:
Before Button Click
After Button Click
Program on MouseOver Event:
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("This is Java MouseOver Event Test Point ");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
Output:
Before Mouse Over Event
After Mouse Over Event
Program on Focus Event:
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
//-->
</script>
</body>
</html>
Output:
Before Entering Data
While Entering Data
Program on Key Down Event:
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
</html>
Output:
Before Key Press
After Key Press
Program on Load Event:
<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
</html>
Output:
Program on Form Validations:
<html>
<body>
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="vuinbox.html" onsubmit="return
validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
Before Click
After Click and Validations Checked
Looping Array Elements:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>Looping an Array</h2>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;
let text = "<ul>";
for (let i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Output:
Adding Array Element:
Way 1- use push function
const fruits = ["Banana", "Orange", "Apple"];
fruits.push("Lemon"); // Adds a new element (Lemon) to fruits
Way 2- use length property
const fruits = ["Banana", "Orange", "Apple"];
fruits[fruits.length] = "Lemon"; // Adds "Lemon" to fruits
Adding elements with high indexes can create undefined "holes" in an array:
const fruits = ["Banana", "Orange", "Apple"];
fruits[6] = "Lemon"; // Creates undefined "holes" in fruits
Banana
Orange
Apple
undefined
undefined
undefined
Lemon
Array Methods
The join() method also joins all array elements into a string.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
Result - Banana * Orange * Apple * Mango
The push() method adds a new element to an array (at the end):
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
Result - Banana,Orange,Apple,Mango,Kiwi
The pop() method removes the last element from an array and returns the value that was
"popped out":
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits.pop();//Mango
document.getElementById("demo2").innerHTML = fruits;// Banana,Orange,Apple
The shift() method removes the first array element and "shifts" all other elements to a
lower index and returns the value that was "shifted out":
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits.shift();//Banana
document.getElementById("demo2").innerHTML = fruits;// Orange,Apple,Mango
The unshift() method adds a new element to an array (at the beginning), and "unshifts"
older elements:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;// Banana,Orange,Apple,Mango
fruits.unshift("Lemon");
document.getElementById("demo2").innerHTML = fruits;// Lemon,Banana,Orange,Apple,Mango
Warning !
● Array elements can be deleted using the JavaScript operator delete.
● Using delete leaves undefined holes in the array.
● Use pop() or shift() instead.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML ="The first fruit is: " + fruits[0];// Banana
delete fruits[0];
document.getElementById("demo2").innerHTML ="The first fruit is: " + fruits[0];//undefined
Merging (Concatenating) Two Arrays:
const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];
const myChildren = myGirls.concat(myBoys);
document.getElementById("demo").innerHTML = myChildren;// Cecilie,Lone,Emil,Tobias,Linus
Merging (Concatenating) Three Arrays:
const array1 = ["Cecilie", "Lone"];
const array2 = ["Emil", "Tobias", "Linus"];
const array3 = ["Robin", "Morgan"];
const myChildren = array1.concat(array2, array3);
document.getElementById("demo").innerHTML = myChildren;//
Cecilie,Lone,Emil,Tobias,Linus,Robin,Morgan
The splice() method can be used to add new items to an array:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
// Banana,Orange,Apple,Mango
fruits.splice(2, 0, "Lemon", "Kiwi");
document.getElementById("demo2").innerHTML = fruits;//
Banana,Orange,Lemon,Kiwi,Apple,Mango
Note – fruits.splice(2, 0, "Lemon", "Kiwi");
The first parameter (2) defines the position where new elements should be added (spliced in).
The second parameter (0) defines how many elements should be removed.
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.
The splice() method returns an array with the deleted items:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = "Original Array:<br> " + fruits;
let removed = fruits.splice(2, 2, "Lemon", "Kiwi");
document.getElementById("demo2").innerHTML = "New Array:<br>" + fruits;
document.getElementById("demo3").innerHTML = "Removed Items:<br> " + removed;
Using splice() to Remove Elements
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;// Banana,Orange,Apple,Mango
fruits.splice(0, 1);
document.getElementById("demo2").innerHTML = fruits;// Orange,Apple,Mango
The slice() method slices out a piece of an array into a new array.
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1);
document.getElementById("demo").innerHTML = fruits + "<br><br>" + citrus;
Output:
Banana,Orange,Lemon,Apple,Mango
Orange,Lemon,Apple,Mango
Note -
● The slice() method creates a new array.
● The slice() method does not remove any elements from the source array.
● When the slice() method is given two arguments, it selects array elements from the start
argument, and up to (but not included) the end argument:
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1,3);
document.getElementById("demo").innerHTML = fruits + "<br><br>" + citrus;
Output:
Banana,Orange,Lemon,Apple,Mango
Orange,Lemon
Automatic toString()
Following two examples will produce the same result:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
Output:
Banana,Orange,Apple,Mango
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>
<p>Click the buttons to sort the array alphabetically or numerically.</p>
<button onclick="myFunction1()">Sort Alphabetically</button>
<button onclick="myFunction2()">Sort Numerically</button>
<p id="demo"></p>
<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;
function myFunction1() {
points.sort();
document.getElementById("demo").innerHTML = points;
}
function myFunction2() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = points;
}
</script>
</body>
</html>
Output:
When Sort Alphabetically Button is Pressed
When Sort Numerically Button is Pressed
Conclusion:
We have learned about conditionals and loops and functions. We extended our understanding into
the realm of Object Oriented Programming and further enhanced the usefulness of all of these
big concepts by practicing how to manipulate the Document Object Model and respond to user
interaction. This has only begun a journey towards proficiency with JavaScript. There are so
many more things to learn, so many challenges to overcome, and so much work to do.
MARKS & SIGNATURE:
R1 R2 R3 R4 Total Signature
(3 Marks) (5 Marks) (4 Marks) (3 Marks) (15 Marks)