JS(Casestudy)
JS(Casestudy)
1. You are creating a web page that greets the user by name. Write a JavaScript program
that asks the user for their name using a prompt () dialog and then displays a greeting
message like “Hello, [name]!” on the web page. Also, explain how prompt () works
and why it is useful for getting user input in JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Greeting Page</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f4f4f9;
margin: 0;
}
h1 {
color: #333;
}
</style>
</head>
<body>
<h1 id="greeting"></h1>
<script>
// Ask the user for their name
const name = prompt("What is your name?");
</body>
</html>
Explanation
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
The <head> section contains metadata and settings for the document that are not
displayed on the webpage.
Sets the character encoding to UTF-8, which supports most characters and symbols
(including special characters like emojis).
Ensures that text and symbols are displayed correctly.
6. <title>Greeting Page</title>
Sets the title of the webpage (shown on the browser tab).
8. body { ... }
font-family: Arial, sans-serif; → Sets the font to Arial (or a sans-serif font if
Arial is unavailable).
display: flex; → Uses Flexbox to align content.
justify-content: center; → Centers the content horizontally.
align-items: center; → Centers the content vertically.
height: 100vh; → Sets the height to 100% of the viewport height.
background-color: #f4f4f9; → Sets the background color to light gray.
margin: 0; → Removes any default margin from the body.
9. h1 { ... }
color: #333; → Sets the text color of the <h1> element to dark gray.
10. <body>
This section contains the JavaScript code that makes the webpage interactive.
prompt() → Opens a dialog box asking the user to input their name.
The user's input is stored in the name variable.
If the user presses "Cancel," name will be null.
Condition Check:
o If name is truthy (not empty or null), it will display a personalized message.
o If name is falsy (empty or null), it will display a default greeting.
16. </body>
17. </html>
✅ How It Works:
1. When the page loads, a prompt() box asks for the user’s name.
2. The input is stored in the name variable.
3. The if...else statement determines the greeting message.
4. The message is displayed inside the <h1> element using innerText.
Output:
➡️Scenario 1:
➡️Scenario 2:
prompt() in JavaScript
The prompt() function is a built-in JavaScript method that allows you to display a dialog
box asking the user for input. It temporarily pauses code execution until the user responds by
either entering text or canceling the dialog.
📌 Syntax:
let input = prompt(message, default);
Parameter Description
message (Optional) A string that is displayed as the message in the dialog box.
default
(Optional) A default value that appears in the input field. If omitted, the input
field is empty.
Return
Returns the user input as a string, or null if the user clicks Cancel.
Value
Good for simple user input like names, ages, or quick confirmations.
Code execution is paused until the user responds, which ensures that the input is
processed before the next step.
🚫 Limitations of prompt()
❌ Limited Customization: The appearance of the prompt box is controlled by the browser
and can't be styled using CSS.
❌ Synchronous Blocking: Code execution stops until the user responds, which can be
inconvenient for larger applications.
❌ Not Ideal for Complex Forms: For more complex user input, using HTML forms and
input elements with event listeners is better.
🚀 Summary:
2. Write a JavaScript program that gets a number from the user using prompt (), checks
whether the number is positive, negative, or zero using if or if-else statements, and
displays the result using alert() or document.write(). Also, explain the purpose and
usage of if and if-else statements in JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Number Checker</title>
</head>
<body>
<script>
num = Number(num);
if (isNaN(num)) {
} else {
if (num > 0) {
} else {
</script>
</body>
</html>
3. You are creating a task management web page where users can add tasks without
reloading the page. The page contains an empty <ul> with the ID "taskList". Write a
JavaScript program that gets user input from a text box, creates a new <li> element
with that input, and appends it to the task list. Also, explain how the Document Object
Model (DOM) represents an HTML page as a tree of nodes and how the document
object is used to access and modify elements.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Task Manager</title>
<style>
body {
background-color: #f4f4f9;
margin: 20px;
h1 {
color: #333;
#taskInput {
padding: 8px;
width: 250px;
border-radius: 4px;
margin-right: 5px;
#addTaskBtn, #stopBtn {
background-color: #28a745;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
margin-left: 5px;
#addTaskBtn:hover {
background-color: #218838;
#stopBtn {
background-color: #dc3545;
#stopBtn:hover {
background-color: #c82333;
ul {
list-style-type: none;
padding: 0;
li {
padding: 8px;
background-color: #e9ecef;
margin-top: 5px;
border-radius: 4px;
</style>
</head>
<body>
<h1>Task Manager</h1>
<ul id="taskList"></ul>
<script>
function addTask() {
listItem.innerText = task;
taskList.appendChild(listItem);
taskInput.value = '';
} else {
addTaskBtn.addEventListener('click', addTask);
// Allow pressing "Enter" key to add a task
addTask();
});
function stopProgram() {
taskInput.disabled = true;
addTaskBtn.disabled = true;
stopBtn.disabled = true;
// Show an alert
alert("Program stopped!");
stopBtn.addEventListener('click', stopProgram);
</script>
</body>
</html>
Explanation
🏗️HTML Explanation
HTML (Hypertext Markup Language) defines the structure of the web page.
1. <!DOCTYPE html>
2. <html lang="en">
3. <head> Section
Sets the character encoding to UTF-8 (supports special characters like ä, é, etc.).
Makes the page responsive for different screen sizes (especially mobile).
width=device-width → Sets the width to the device’s screen size.
initial-scale=1.0 → Sets the zoom level to 1.
✅ <title>Task Manager</title>
4. <style> Section
✅ body Styling
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
margin: 20px;
}
font-family: Arial, sans-serif; → Sets font style.
background-color: #f4f4f9; → Light gray background.
margin: 20px; → Adds space around the page content.
✅ h1 Styling
h1 {
color: #333;
}
✅ #taskInput Styling
#taskInput {
padding: 8px;
width: 250px;
border: 1px solid #ccc;
border-radius: 4px;
margin-right: 5px;
}
✅ #addTaskBtn Styling
#addTaskBtn {
padding: 8px 12px;
background-color: #28a745;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
#addTaskBtn:hover {
background-color: #218838;
}
ul {
list-style-type: none;
padding: 0;
}
✅ li Styling
li {
padding: 8px;
background-color: #e9ecef;
margin-top: 5px;
border-radius: 4px;
}
5. <body> Section
✅ Heading
<h1>Task Manager</h1>
✅ Input Box
✅ Task List
<ul id="taskList"></ul>
🎯 JavaScript Explanation
taskList.appendChild(listItem);
taskInput.value = '';
} else {
alert("Please enter a valid task.");
}
}
4. You are developing a budgeting tool for a personal finance web app. Write a
JavaScript program that defines a global variable for income, a function
calculateBalance() that takes an expense amount, validates it using another function,
and then calculates and displays the remaining balance. Also, explain how functions
are defined in JavaScript, the concept of scope rules (global and local), and the role of
global functions in a program.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Budgeting Tool</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
margin: 20px;
}
h1 {
color: #333;
}
input, button {
padding: 8px;
margin: 5px;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
background-color: #28a745;
color: white;
cursor: pointer;
}
button:hover {
background-color: #218838;
}
#balance {
margin-top: 20px;
font-size: 18px;
color: #333;
}
</style>
</head>
<body>
<script>
// Global variable for income (accessible throughout the program)
let totalIncome = 0;
</body
Explanation
Concepts Explained:
1. Functions in JavaScript
function functionName(parameters) {
// code block
}
Example:
function testScope() {
let localVar = 50; // Local variable
console.log(globalVar); // ✅ Accessible
console.log(localVar); // ✅ Accessible inside the function
}
console.log(globalVar); // ✅ Accessible
console.log(localVar); // ❌ Error! localVar is not defined globally
Global functions: