0% found this document useful (0 votes)
4 views10 pages

JavaScript Coding Examples and Exercises

The document contains a comprehensive collection of JavaScript code snippets demonstrating various programming concepts such as variable declarations, functions, loops, conditionals, and event handling. It includes practical examples like grocery shopping, calculating areas, generating emails, and handling user interactions. Additionally, it features HTML structure to integrate the JavaScript files, showcasing a complete web development approach.

Uploaded by

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

JavaScript Coding Examples and Exercises

The document contains a comprehensive collection of JavaScript code snippets demonstrating various programming concepts such as variable declarations, functions, loops, conditionals, and event handling. It includes practical examples like grocery shopping, calculating areas, generating emails, and handling user interactions. Additionally, it features HTML structure to integrate the JavaScript files, showcasing a complete web development approach.

Uploaded by

mandeqdurrow0909
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

// 1.

Grocery Shopping
let product = "Milk";
let price = 20;
[Link]("Ali bought " + product + " for $" + price);

// 2. Circle Area
const PI = 3.14159;
let radius = 5;
let area = PI * radius * radius;
[Link]("Area = " + area);

// 3. Email Generator
let username = "ali";
let provider = "[Link]";
let email = username + "@" + provider;
[Link](email);

// 4. Pizza Sharing
let slices = 10;
let friends = 3;
let each = [Link](slices / friends);
let remaining = slices % friends;
[Link]("Each gets: " + each);
[Link]("Remaining: " + remaining);

// 5. Voting Age Check


let age = 18;
let canVote = age >= 18;
[Link](canVote);

// 6. Login System
let correctUser = "admin";
let correctPass = "1234";
let user = "admin";
let pass = "1234";
let login = (user === correctUser) && (pass === correctPass);
[Link](login);

// 7. Discount Offer
let customerType = "VIP";
let discount = (customerType === "VIP") ? 20 : 5;
[Link]("Discount: " + discount + "%");

// 8. Step Counter
let steps = 10;
steps++; // forward
steps--; // backward
[Link]("Steps: " + steps);

// 9. Checking Data Types


let score = 95;
let name = "Fatima";
[Link](typeof score);
[Link](typeof name);

// 10. Restaurant Bill


let bill = "200";
let tip = 50;
let total = bill + tip;
[Link](total);
// 1. Concert Ticket
let saraName = "Sara";
let saraTickets = 3;
let saraPrice = 25;
let saraTotal = saraTickets * saraPrice;
[Link](`${saraName} buys ${saraTickets} tickets and pays $${saraTotal}`);

// 2. Flight Booking
let aliName = "Ali";
let aliTicket = 12345;
let aliRoute = "Nairobi to Dubai";
[Link](`${aliName} booked ticket number ${aliTicket} for the flight from $
{aliRoute}`);

// 3. Classroom Chairs
let aminaChair = "Omar's chair";
let omarChair = "Amina's chair";
let tempChair = aminaChair;
aminaChair = omarChair;
omarChair = tempChair;
[Link](`Amina sits on ${aminaChair} and Omar sits on ${omarChair}`);

// 4. Bank Account Transfer


let ahmedCard = "Fatima's card";
let fatimaCard = "Ahmed's card";
let tempCard = ahmedCard;
ahmedCard = fatimaCard;
fatimaCard = tempCard;
[Link](`Ahmed has ${ahmedCard} and Fatima has ${fatimaCard}`);

// 5. Café Discount (Single Alternative)


let coffeeCups = 6;
let coffeePrice = 5;
let coffeeTotal = coffeeCups * coffeePrice;
let coffeeDiscount = 0;
if (coffeeCups > 5) {
coffeeDiscount = coffeeTotal * 0.10;
}
let coffeeFinal = coffeeTotal - coffeeDiscount;
[Link](`Total price after discount: $${coffeeFinal}`);

// 6. Pass or Fail (Dual Alternative)


let examScore = 45;
if (examScore >= 50) {
[Link]("Passed");
} else {
[Link]("Failed");
}

// 7. Movie Ticket Price (Multi Alternative)


let personAge = 65;
let moviePrice;
if (personAge < 12) {
moviePrice = 5;
} else if (personAge <= 60) {
moviePrice = 10;
} else {
moviePrice = 7;
}
[Link](`Ticket price: $${moviePrice}`);

// 8. Scholarship (Nested If Else)


let studentAverage = 92;
if (studentAverage > 80) {
if (studentAverage > 90) {
[Link]("Full scholarship");
} else {
[Link]("Half scholarship");
}
} else {
[Link]("No scholarship");
}

// 9. School Timetable (Switch with String)


let day = "Wednesday";
switch (day) {
case "Monday":
[Link]("Math Club");
break;
case "Wednesday":
[Link]("Science Lab");
break;
case "Friday":
[Link]("Sports Day");
break;
default:
[Link]("No activity today");
}

// 10. Restaurant Menu (Switch with Number)


let menuChoice = 2;
switch (menuChoice) {
case 1:
[Link]("Pizza");
break;
case 2:
[Link]("Burger");
break;
case 3:
[Link]("Salad");
break;
default:
[Link]("Invalid choice");
}

// 11. Hospital Department (Switch with String)


let department = "Dermatology";
switch (department) {
case "Cardiology":
[Link]("Heart Department");
break;
case "Dermatology":
[Link]("Skin Department");
break;
case "Pediatrics":
[Link]("Children Department");
break;
default:
[Link]("Department not found");
}

// 12. Bus Route Number (Switch with Number)


let busNum = 202;
switch (busNum) {
case 101:
[Link]("Airport");
break;
case 202:
[Link]("Train Station");
break;
case 303:
[Link]("Shopping Mall");
break;
default:
[Link]("Unknown bus number");
}

// 13. School Grade Levels (Switch with Number)


let grade = 2;
switch (grade) {
case 1:
[Link]("Primary");
break;
case 2:
[Link]("Middle School");
break;
case 3:
[Link]("High School");
break;
default:
[Link]("Invalid grade");
}

// 14. Weather Forecast (Switch with String)


let weather = "Rainy";
switch (weather) {
case "Sunny":
[Link]("Wear sunglasses");
break;
case "Rainy":
[Link]("Carry an umbrella");
break;
case "Cold":
[Link]("Wear a jacket");
break;
default:
[Link]("No advice available");
}
// Daily Steps Tracker
for (let day = 1; day <= 7; day++) {
[Link](`Day ${day}: Keep walking!`);
}

// Even Numbers Display


for (let i = 2; i <= 20; i++) {
if (i % 2 === 0) [Link](i);
}

// Password Attempt
let userPassword = "";
while (userPassword !== "1234") {
userPassword = "1234";
}
[Link]("Logged in!");

// Temperature Reader
let currentTemp;
do {
currentTemp = 0;
} while (currentTemp !== 0);
[Link]("Temperature reading ended.");

// Quiz Retake
let quizScore;
do {
quizScore = 50;
} while (quizScore < 50);
[Link]("Quiz completed.");

// Customer Queue
for (let customer = 1; customer <= 10; customer++) {
if (customer === 5) break;
[Link](`Serving customer ${customer}`);
}

// Odd Number Skipper


for (let i = 1; i <= 10; i++) {
if (i % 2 !== 0) continue;
[Link](i);
}

// Number Collector
let nums = [5, 3, 8, -1];
let count = 0;
for (let num of nums) {
if (num === -1) break;
count++;
}
[Link](count);

// Total Grocery Cost


let priceList = [50, 30, 20, 0];
let totalCost = 0;
for (let price of priceList) {
if (price === 0) break;
totalCost += price;
}
[Link](totalCost);

// Multiplication Table
for (let i = 1; i <= 5; i++) {
let row = "";
for (let j = 1; j <= 5; j++) {
row += `${i * j} `;
}
[Link](row);
}

// Seating Arrangement
for (let row = 1; row <= 3; row++) {
for (let seat = 1; seat <= 4; seat++) {
[Link](`Row ${row} Seat ${seat}`);
}
}
// Greeting Based on Time
function greetUser(name, hour) {
if (hour < 12)
[Link](`Good Morning, ${name}`);
else if (hour < 18)
[Link](`Good Afternoon, ${name}`);
else
[Link](`Good Evening, ${name}`);
}
greetUser("Mandeq", 10);
greetUser("Mandeq", 15);
greetUser("Mandeq", 20);

// Check Voting Eligibility


function checkVotingAge(age) {
if (age >= 18) [Link]("You are eligible to vote.");
else [Link]("You are not eligible to vote yet.");
}
checkVotingAge(16);
checkVotingAge(20);

// Calculate Total Price


function calculateTotal(price, quantity) {
let total = price * quantity;
if (total > 100) {
[Link]("You get a 10% discount!");
total = total * 0.9;
}
return total;
}
[Link](calculateTotal(20, 3));
[Link](calculateTotal(15, 8));

// Even or Odd Checker


function checkEvenOdd(limit) {
for (let i = 1; i <= limit; i++) {
if (i % 2 === 0)
[Link](`${i} is Even`);
else
[Link](`${i} is Odd`);
}
}
checkEvenOdd(10);

// Student Grade Evaluator


function calculateGrade(score) {
if (score >= 90) [Link]("A");
else if (score >= 80) [Link]("B");
else if (score >= 70) [Link]("C");
else [Link]("Fail");
}
calculateGrade(95);
calculateGrade(85);
calculateGrade(72);
calculateGrade(60);

// Default Parameter
function makeCoffee(type = "Black Coffee", sugar = 1) {
[Link](`Making ${type} with ${sugar} spoon(s) of sugar.`);
if (sugar > 3)
[Link]("That's too much sugar!");
}
makeCoffee();
makeCoffee("Latte", 2);
makeCoffee("Cappuccino", 5);

// Multiplication Table Using Loop


function printTable(number) {
for (let i = 1; i <= 10; i++) {
[Link](`${number} × ${i} = ${number * i}`);
}
}
printTable(5);

// Simple ATM Function


function withdrawMoney(balance, amount) {
if (amount <= balance) {
balance -= amount;
return balance;
} else {
[Link]("Insufficient funds.");
return balance;
}
}
[Link](withdrawMoney(500, 200));
[Link](withdrawMoney(500, 600));
(() => {

// Global and Local Scope


let hospitalName = "City Hospital";
function displayInfo() {
let department = "Cardiology";
[Link](hospitalName);
[Link](department);
}
displayInfo();
// Block Scope (let and var)
let totalBill = 150;
if (totalBill > 100) {
let discountMsg = "You get a discount!";
var note = "Bill checked";
[Link](discountMsg);
[Link](note);
}
[Link](typeof discountMsg); // undefined
[Link](note); // "Bill checked"

// Function Expression – Greeting Message


const greetUser = function(name) {
[Link](`Welcome, ${name}!`);
};
greetUser("Ali");
greetUser("Fatima");

// Function Expression – Area Calculator


const rectangleArea = function(length, width) {
return length * width;
};
[Link](rectangleArea(5, 10));

// Arrow Function – Temperature Check


const checkTemp = temp => {
if (temp > 30) [Link]("Hot day");
else [Link]("Cool day");
};
checkTemp(32);
checkTemp(25);

// Arrow Function – Age Eligibility


const checkAge = age => {
if (age >= 18) [Link]("Eligible");
else [Link]("Not eligible");
};
checkAge(20);
checkAge(16);

// Nested Scope
function library() {
let libraryName = "Central Library";
function section() {
let sectionName = "Fiction";
[Link](libraryName);
[Link](sectionName);
}
section();
}
library();

// Callback Function – Step-by-Step Task


function cleanRoom(callback) {
[Link]("Room cleaned.");
callback();
}
function sanitizeRoom() {
[Link]("Room sanitized.");
}
cleanRoom(sanitizeRoom);

// Anonymous Callback Function – Payment Confirmation


function processPayment(callback) {
callback();
}
processPayment(function() {
[Link]("Payment successful.");
});

// Callback with Delay – Delivery Notification


[Link]("Order confirmed.");
setTimeout(function() {
[Link]("Your order has been delivered!");
}, 3000);

// Arrow Function + Callback


function register(callback) {
[Link]("Data saved.");
callback();
}
register(() => [Link]("Registration successful."));

// Function Expression + Scope


let bankName = "Global Bank";
const showBank = function() {
let branch = "Downtown Branch";
[Link](bankName);
[Link](branch);
};
showBank();

// Callback Function – Login System


function checkUser(callback) {
[Link]("User verified.");
callback();
}
function welcomeUser() {
[Link]("Welcome to your account.");
}
checkUser(welcomeUser);

// Anonymous Callback – Cooking Steps


[Link]("Cooking started.");
setTimeout(function() {
[Link]("Food is ready!");
}, 2000);

// Mixing Concepts – Job Application Process


function collectInfo(callback) {
[Link]("Information collected.");
callback();
}
collectInfo(function() {
[Link]("Application processed.");
(() => [Link]("Thank you for applying!"))();
});

})();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="[Link]"></script>
<script src="[Link]"></script>
<script src="[Link]"></script>
<script src="[Link]"></script>
<script src="[Link]"></script>

</body>
</html>

You might also like