ToSubmitJavaScript (1)
ToSubmitJavaScript (1)
ToSubmitJavaScript (1)
// Variables
const num1 = 10;
const num2 = 5;
// Conditions
document.write('Num1 is greater.<br>');
// While Loop
letwhileCounter = 1;
while (whileCounter<= 5) {
document.write(`While loop iteration ${whileCounter}<br>`);
whileCounter++;
}
// For Loop
for (let forCounter = 1; forCounter<= 5; forCounter++) {
document.write(`For loop iteration ${forCounter}<br>`);
}
// Do-While Loop
letdoWhileCounter = 1;
do {
document.write(`Do while loop iteration ${doWhileCounter}<br>`);
doWhileCounter++;
} while (doWhileCounter<= 5);
// Switch Statement
constdayOfWeek = 'Monday';
switch (dayOfWeek) {
case 'Monday':
document.write('It\'s Monday.<br>');
break;
default:
document.write('It\'s not Monday.<br>');
}
</script>
</body>
</html>
OUTPUT:
2. Write a program to demonstrate different array and string
methods in JavaScript?
CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array and String Methods Demo</title>
</head>
<body>
<h2>Array Methods</h2>
<pre id="array-output"></pre>
<h2>String Methods</h2>
<pre id="string-output"></pre>
<script>
// Array Methods
const numbers = [1, 2, 3, 4, 5];
// 1. push() - Add an element to the end of the array
numbers.push(6);
document.getElementById('array-output').innerText += `push: $
{JSON.stringify(numbers)}\n`;
// String Methods
const greeting = 'Hello, World!';
// 8. length - Get the length of the string
conststringLength = greeting.length;
document.getElementById('string-output').innerText += `length: $
{stringLength}\n`;
// 17. trim() - Remove whitespaces from the beginning and end of a string
conststringWithWhitespaces = ' Trim Me! ';
consttrimmedString = stringWithWhitespaces.trim();
document.getElementById('string-output').innerText += `trim: $
{trimmedString}\n`;
</script>
</body>
</html>
OUTPUT:
3.Write a program to show different ways to create a function
in JavaScript?
CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Function Creation in JavaScript</title>
</head>
<body>
<script>
// 1. Function Declaration
functiondeclarationFunction(name) {
return `Hello, ${name} (Function Declaration)`;
}
// 2. Function Expression
constexpressionFunction = function(name) {
return `Hello, ${name} (Function Expression)`;
};
// 3. Arrow Function
constarrowFunction = (name) => `Hello, ${name} (Arrow Function)`;
// 4. Function Constructor (not recommended due to security and
performance concerns)
constconstructorFunction = new Function('name', 'return "Hello, " +
name + " (Function Constructor)"');
// 5. Immediately Invoked Function Expression (IIFE)
constiifeResult = (function(name) {
return `Hello, ${name} (IIFE)`;
})('Eve');
// 6. Generator Function
function* generatorFunction(name) {
yield `Hello, ${name} (Generator Function)`;
}
// 7. Function returning a Function
functioncreateGreeter(greeting) {
return function(name) {
return `${greeting}, ${name} (Returned Function)`;
};
}
constgreetWithHey = createGreeter('Hey');
// 8. Object Method
constobj = {
method: function(name) {
return `Hello, ${name} (Object Method)`;
}
};
// Displaying the results on the page
document.write('<p>' + declarationFunction('Alice') + '</p>');
document.write('<p>' + expressionFunction('Bob') + '</p>');
document.write('<p>' + arrowFunction('Charlie') + '</p>');
document.write('<p>' + constructorFunction('Dave') + '</p>');
document.write('<p>' + iifeResult + '</p>');
#timer-container {
background-color: #333;
}
#timer {
font-size: 3em;
color: white;
}
#controls, #buttons {
background-color: #4CAF50;
}
button {
font-size: 1.2em;
margin: 0 5px;
padding: 10px 15px;
cursor: pointer;
border: none;
border-radius: 5px;
}
#session-length, #break-length {
font-size: 1.5em;
margin: 0 10px;
padding: 10px 20px;
border-radius: 30px;
text-align: center;
color: white;
}
#reset, #start {
background-color: #000000;
color: white;
}
</style>
</head>
<body>
<div id="timer-container" class="row">
<div id="timer">25:00</div>
</div>
<button id="break-decrement">-</button>
<div id="break-length">5</div>
<button id="break-increment">+</button>
</div>
<script>
let timer;
lettimeLeft = 25 * 60; // Initial time in seconds
letisRunning = false;
functionupdateTimerDisplay() {
const minutes = Math.floor(timeLeft / 60);
const seconds = timeLeft % 60;
document.getElementById('timer').innerText = `${String(minutes).padStart(2,
'0')}:${String(seconds).padStart(2, '0')}`;
}
functionstartTimer() {
if (!isRunning) {
timer = setInterval(() => {
if (timeLeft> 0) {
timeLeft--;
updateTimerDisplay();
} else {
clearInterval(timer);
isRunning = false;
alert('Pomodoro session completed!');
}
}, 1000);
isRunning = true;
}
}
functionresetTimer() {
clearInterval(timer);
isRunning = false;
timeLeft = 25 * 60;
updateTimerDisplay();
}
document.getElementById('session-decrement').addEventListener('click', () => {
constsessionLengthElement = document.getElementById('session-length');
letsessionLength = parseInt(sessionLengthElement.innerText);
if (sessionLength> 1) {
sessionLength--;
sessionLengthElement.innerText = sessionLength;
if (!isRunning) {
timeLeft = sessionLength * 60;
updateTimerDisplay();
}
}
});
document.getElementById('session-increment').addEventListener('click', () => {
constsessionLengthElement = document.getElementById('session-length');
letsessionLength = parseInt(sessionLengthElement.innerText);
if (sessionLength< 60) {
sessionLength++;
sessionLengthElement.innerText = sessionLength;
if (!isRunning) {
timeLeft = sessionLength * 60;
updateTimerDisplay();
}
}
});
document.getElementById('break-decrement').addEventListener('click', () => {
constbreakLengthElement = document.getElementById('break-length');
letbreakLength = parseInt(breakLengthElement.innerText);
if (breakLength> 1) {
breakLength--;
breakLengthElement.innerText = breakLength;
}
});
document.getElementById('break-increment').addEventListener('click', () => {
constbreakLengthElement = document.getElementById('break-length');
letbreakLength = parseInt(breakLengthElement.innerText);
if (breakLength< 60) {
breakLength++;
breakLengthElement.innerText = breakLength;
}
});
document.getElementById('start').addEventListener('click', startTimer);
document.getElementById('reset').addEventListener('click', resetTimer);
updateTimerDisplay();
</script>
</body>
</html>
OUTPUT:
5. Write a program to implement swap 1 to 9 numbers using drag
and drop?
CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Swap Numbers</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.grid {
display: grid;
grid-template-columns: repeat(3, 50px);
grid-template-rows: repeat(3, 50px);
border: 1px solid black;
}
.cell {
width: 48px;
height: 48px;
background-color: lightgray;
text-align: center;
line-height: 48px;
font-size: 16px;
cursor: pointer;
border: 1px solid black;
float: left;
}
.cell:nth-child(3n+1) {
clear: left;
}
</style>
</head>
<body>
<script>
letdragSrcEl = null;
functiondragStart(event) {
event.dataTransfer.effectAllowed = 'move';
event.dataTransfer.setData('text/html', event.target.innerHTML);
dragSrcEl = event.target;
}
functiondragOver(event) {
if (event.preventDefault) {
event.preventDefault();
}
event.dataTransfer.dropEffect = 'move';
return false;
}
function drop(event) {
if (event.stopPropagation) {
event.stopPropagation();
}
if (dragSrcEl !== event.target) {
dragSrcEl.innerHTML = event.target.innerHTML;
event.target.innerHTML = event.dataTransfer.getData('text/html');
}
return false;
}
</script>
</body>
</html>
OUTPUT:
<script>
// 2. Arrow Functions
const add = (a, b) => a + b;
const multiply = (a, b) => {
return a * b;
};
// 3. Template literals
const name = 'John';
const greeting = `Hello, ${name}!`;
// 4. Destructuring assignment
const person = { firstName: 'Alice', lastName: 'Doe' };
const { firstName, lastName } = person;
// 5. Default parameters
const greet = (name = 'Guest') => `Hello, ${name}!`;
// 7. Classes
class Animal {
constructor(name) {
this.name = name;
}
makeSound() {
return 'Generic animal sound';
}
}
// 8. Promises
constfetchData = () => {
return new Promise((resolve, reject) => {
// Simulating asynchronous data fetching
setTimeout(() => {
const data = 'Fetched data';
resolve(data);
}, 2000);
});
};
fetchData()
.then(data => console.log('Data:', data))
.catch(error =>console.error('Error:', error));
</script>
</body>
</html>