0% found this document useful (0 votes)
17 views

ToSubmitJavaScript (1)

Uploaded by

khushibanchhor21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

ToSubmitJavaScript (1)

Uploaded by

khushibanchhor21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Name : Ajay Pratap Kerketta

Course: Full Stack Development


JDBC Assignment
Batch: 15/9/2023
Email:[email protected]
JavaScript

1.Write a program to demonstrate JavaScript loops, operators and


conditions?
CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Loops, Operators, and Conditions</title>
</head>
<body>
<script>

// 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`;

// 2. pop() - Remove the last element from the array


constpoppedElement = numbers.pop();
document.getElementById('array-output').innerText += `pop: $
{JSON.stringify(numbers)}, popped: ${poppedElement}\n`;

// 3. unshift() - Add an element to the beginning of the array


numbers.unshift(0);
document.getElementById('array-output').innerText += `unshift: $
{JSON.stringify(numbers)}\n`;

// 4. shift() - Remove the first element from the array


constshiftedElement = numbers.shift();
document.getElementById('array-output').innerText += `shift: $
{JSON.stringify(numbers)}, shifted: ${shiftedElement}\n`;

// 5. slice() - Extract a portion of the array


constslicedArray = numbers.slice(1, 4);
document.getElementById('array-output').innerText += `slice: $
{JSON.stringify(numbers)}, sliced: ${JSON.stringify(slicedArray)}\n`;

// 6. splice() - Remove or replace elements at a specific index


numbers.splice(2, 1, 'a', 'b');
document.getElementById('array-output').innerText += `splice: $
{JSON.stringify(numbers)}\n`;

// 7. indexOf() - Find the index of a specific element


const index = numbers.indexOf('a');
document.getElementById('array-output').innerText += `indexOf: ${index}\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`;

// 9. toUpperCase() - Convert the string to uppercase


constupperCaseGreeting = greeting.toUpperCase();
document.getElementById('string-output').innerText += `toUpperCase: $
{upperCaseGreeting}\n`;

// 10. toLowerCase() - Convert the string to lowercase


constlowerCaseGreeting = greeting.toLowerCase();
document.getElementById('string-output').innerText += `toLowerCase: $
{lowerCaseGreeting}\n`;

// 11. charAt() - Get the character at a specific index


constcharAtIndex = greeting.charAt(7);
document.getElementById('string-output').innerText += `charAt: $
{charAtIndex}\n`;

// 12. substring() - Extract a portion of the string


const substring = greeting.substring(7, 12);
document.getElementById('string-output').innerText += `substring: $
{substring}\n`;

// 13. replace() - Replace a substring with another substring


constreplacedString = greeting.replace('World', 'Universe');
document.getElementById('string-output').innerText += `replace: $
{replacedString}\n`;

// 14. split() - Split the string into an array of substrings


constsplitArray = greeting.split(', ');
document.getElementById('string-output').innerText += `split: $
{JSON.stringify(splitArray)}\n`;
// 15. includes() - Check if a string includes another string
constincludesCheck = greeting.includes('Hello');
document.getElementById('string-output').innerText += `includes: $
{includesCheck}\n`;

// 16. indexOf() - Find the index of a specific substring


constindexOfSubstring = greeting.indexOf('World');
document.getElementById('string-output').innerText += `indexOf: $
{indexOfSubstring}\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>');

const generator = generatorFunction('World');


document.write('<p>' + generator.next().value + '</p>');

document.write('<p>' + greetWithHey('Frank') + '</p>');


document.write('<p>' + obj.method('Grace') + '</p>');
</script>
</body>
</html>
OUTPUT:
4. Write a program to implement pomodoro using JavaScript
DOM?
CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pomodoro Timer</title>
<style>
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
font-family: 'Arial', sans-serif;
background-color: #f4f4f4;
}
.row {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 70px;
margin: 5px 0;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

#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>

<div id="controls" class="row">


<button id="session-decrement">-</button>
<div id="session-length">25</div>
<button id="session-increment">+</button>

<button id="break-decrement">-</button>
<div id="break-length">5</div>
<button id="break-increment">+</button>
</div>

<div id="buttons" class="row">


<button id="reset">Reset</button>
<button id="start">Start</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>

<div class="grid" id="grid">


<div class="cell" id="1" draggable="true" ondragstart="dragStart(event)"
ondragover="dragOver(event)" ondrop="drop(event)">1</div>
<div class="cell" id="2" draggable="true" ondragstart="dragStart(event)"
ondragover="dragOver(event)" ondrop="drop(event)">2</div>
<div class="cell" id="3" draggable="true" ondragstart="dragStart(event)"
ondragover="dragOver(event)" ondrop="drop(event)">3</div>
<div class="cell" id="4" draggable="true" ondragstart="dragStart(event)"
ondragover="dragOver(event)" ondrop="drop(event)">4</div>
<div class="cell" id="5" draggable="true" ondragstart="dragStart(event)"
ondragover="dragOver(event)" ondrop="drop(event)">5</div>
<div class="cell" id="6" draggable="true" ondragstart="dragStart(event)"
ondragover="dragOver(event)" ondrop="drop(event)">6</div>
<div class="cell" id="7" draggable="true" ondragstart="dragStart(event)"
ondragover="dragOver(event)" ondrop="drop(event)">7</div>
<div class="cell" id="8" draggable="true" ondragstart="dragStart(event)"
ondragover="dragOver(event)" ondrop="drop(event)">8</div>
<div class="cell" id="9" draggable="true" ondragstart="dragStart(event)"
ondragover="dragOver(event)" ondrop="drop(event)">9</div>
</div>

<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:

6. Demonstrate all ES6 concepts with examples.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ES6 Concepts</title>
</head>
<body>

<script>

// 1. let and const


letvariableExample = 'I can be changed';
constconstantExample = 'I cannot be changed';

// 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}!`;

// 6. Spread and rest operators


const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
constcombinedArray = [...arr1, ...arr2];

constsumNumbers = (...numbers) =>numbers.reduce((acc, num) =>acc + num,


0);

// 7. Classes
class Animal {
constructor(name) {
this.name = name;
}

makeSound() {
return 'Generic animal sound';
}
}

class Dog extends Animal {


makeSound() {
return 'Woof!';
}
}

constmyDog = new Dog('Buddy');

// 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>

You might also like