JavaScript exercises
🔹 Arrays
1. Create an array of 5 numbers. Print each number using a loop.
2. Find the sum of all elements in an array.
3. Find the largest number in an array.
4. Reverse an array and print it.
5. Remove the first element from an array and print the updated array.
6. Check if a particular element exists in an array.
7. Sort an array of numbers in ascending order.
8. Merge two arrays and print the resulting array.
9. Create an array of names and print only the names with length greater than 4.
10. Replace the third element of an array with a new value.
🔹 Functions
11. Write a function that takes a number as input and returns its square.
12. Write a function that takes two numbers and returns the larger number.
13. Write a function that checks if a given string is a palindrome.
14. Write a function that accepts an array and returns the sum of its elements.
15. Write a function to count the number of vowels in a given string.
16. Write a function that returns true if a number is prime, else false.
17. Write a function to convert Celsius to Fahrenheit.
18. Write a function to find factorial of a given number.
19. Write a function that accepts an array and returns a new array with each element doubled.
20. Write a function that joins an array of words into a single sentence.
Grocery List Management
● Create an array called groceryList with three items: "apple", "banana", and "carrot".
● Write a function addItem(item) that adds a new item to the list.
● Write a function removeItem(item) that removes an item from the list.
● Write a function displayList() that logs the current grocery list to the console.
// Create the array
let groceryList = ["apple", "banana", "carrot"];
// Function to add an item
function addItem(item) {
groceryList.push(item);
// Function to remove an item
function removeItem(item) {
let index = groceryList.indexOf(item);
if (index !== -1) {
groceryList.splice(index, 1);
} else {
console.log(item + " not found in the list.");
// Function to display the list
function displayList() {
console.log("Grocery List:", groceryList);
// Testing
displayList(); // ["apple", "banana", "carrot"]
addItem("mango");
displayList(); // ["apple", "banana", "carrot", "mango"]
removeItem("banana");
displayList(); // ["apple", "carrot", "mango"]
removeItem("grapes"); // grapes not found in the list.
Student Grade Tracker
● Create an object students where each key is a student name and the value is their grade
(e.g., "John": 85).
● Write a function addGrade(name, grade) that adds or updates a student's grade.
● Write a function getAverageGrade() that calculates and returns the average grade of all
students.
. Event Registration Form
Scenario: You are building an event registration system. When a user enters their name, email,
and age, the system should check if the user meets the age requirement and return an appropriate
response.
● Task:
1. Create a function checkEligibility(name, email, age) that takes a user’s
name, email, and age.
2. If the user is under 18, return "You must be at least 18 to register."
3. If the user is eligible, return "Thank you for registering, [name]!"
. Library Book Management
Scenario: You are building a library system where you need to track books. Each book has a
title, author, and availability status.
● Task:
1. Create an array of books, each with properties: title, author, and available
(boolean).
2. Write a function borrowBook(title) that sets the available status of the book
to false when a book is borrowed.
3. Write a function returnBook(title) that sets the available status of the book
to true when a book is returned.
4. Write a function listAvailableBooks() that lists all books that are available.
. Simple Online Store Checkout
Scenario: You are building a simple online store checkout system. The store sells products and
applies a discount based on the total price.
● Task:
1. Create an array products where each product is an object with name and price.
2. Write a function calculateTotal(cart) that calculates the total price of items
in the cart.
3. Write a function applyDiscount(total) that applies a 10% discount if the total
is greater than $50.
4. Write a function checkout(cart) that calculates the final price after applying the
discount.
. Movie Rating System
Scenario: You are building a system where users can rate movies from 1 to 5 stars.
● Task:
1. Create an object movies with the movie names as keys and their ratings (an array)
as values.
2. Write a function addRating(movie, rating) that adds a rating to a movie's list
of ratings.
3. Write a function getAverageRating(movie) that calculates and returns the
average rating for a movie.
4. Write a function getHighestRatedMovie() that returns the movie with the
highest average rating.
. Simple Bank Account
Scenario: You are building a simple bank account system where a user can deposit and
withdraw money.
● Task:
1. Create an object account with properties: balance (initially 0),
deposit(amount), and withdraw(amount).
2. The deposit(amount) function should increase the balance by the given amount.
3. The withdraw(amount) function should decrease the balance by the given
amount if there are sufficient funds, otherwise, return an error message.
. Fitness Tracker
Scenario: You are building a fitness tracker where a user can log their daily steps and calculate
the total steps over a week.
● Task:
1. Create an array steps where each element represents the steps taken each day of
the week.
2. Write a function logSteps(day, stepCount) that logs the steps for a specific
day.
3. Write a function getTotalSteps() that calculates the total steps taken over the
week.
. Task List Manager
Scenario: You are building a task management app where users can add, complete, and remove
tasks.
● Task:
1. Create an array tasks where each element is an object with a taskName and a
completed status (boolean).
2. Write a function addTask(taskName) that adds a new task to the task list.
3. Write a function completeTask(taskName) that sets the task’s completed status
to true.
4. Write a function removeTask(taskName) that removes a task from the list.
5. Write a function displayTasks() that displays all tasks, showing whether they
are completed or not.
. Online Survey
Scenario: You are building an online survey where users can select their preferred programming
language from a list.
● Task:
1. Create an array languages containing the list of programming languages.
2. Create a function takeSurvey(choice) that allows users to select a programming
language.
3. Keep track of how many users select each language.
4. Write a function getResults() that returns the programming language with the
highest number of selections.
. Temperature Logger
Scenario: You are building a weather tracker that logs the daily temperature and reports on it.
● Task:
1. Create an array temperatures where each element represents the temperature
recorded for a day.
2. Write a function logTemperature(temp) that logs the temperature for a day.
3. Write a function getHighestTemperature() that returns the highest recorded
temperature.
4. Write a function getAverageTemperature() that calculates the average
temperature over the logged days.
. Task Reminder
Scenario: You are building a task reminder app where users can set a reminder for a task that
needs to be completed within a certain number of days.
● Task:
1. Create an object tasks where each key is the task name and each value is an
object with properties: daysLeft (number of days until the task is due) and
reminderSet (boolean).
2. Write a function setReminder(taskName, days) that sets the daysLeft for the
task and marks reminderSet as true.
3. Write a function getReminder(taskName) that returns a message like "Reminder
set for [taskName], [daysLeft] days left."
4. Write a function checkDueTasks() that checks if any tasks are due today and
logs them.
. Online Quiz
Scenario: You are creating a simple quiz app where users can answer multiple-choice questions
and get a score.
● Task:
1. Create an array questions where each question is an object with properties:
questionText, options (array of options), and correctAnswer.
2. Write a function answerQuestion(questionIndex, answer) that checks if the
provided answer matches the correct answer.
3. Write a function getScore() that calculates and returns the user’s score based on
correct answers.
. Simple Voting System
Scenario: You are building a voting system where users can vote for one of the candidates.
● Task:
1. Create an object candidates where each key is the candidate's name and each
value is the number of votes they have.
2. Write a function voteForCandidate(candidateName) that increments the vote
count for the specified candidate.
3. Write a function getWinner() that returns the candidate with the highest number
of votes.
. Flight Booking System
Scenario: You are building a flight booking system where users can search for flights and book
seats.
● Task:
1. Create an array flights where each flight is an object containing flightNumber,
destination, seatsAvailable.
2. Write a function bookFlight(flightNumber) that decreases the
seatsAvailable by 1 if there are seats available.
3. Write a function searchFlight(destination) that returns a list of flights going
to the specified destination.
. Simple Contact List
Scenario: You are building a contact list application where users can store, update, and remove
contacts.
● Task:
1. Create an array contacts where each element is an object with properties name,
phone, and email.
2. Write a function addContact(contact) that adds a new contact to the list.
3. Write a function removeContact(name) that removes a contact based on the
name.
4. Write a function updateContact(name, updatedInfo) that updates a contact's
information.
Here are additional scenario-based JavaScript exercises:
. Online Auction System
Scenario: You are building an online auction system where users can place bids on an item.
● Task:
1. Create an object auctionItem with properties: itemName, currentBid, and
bidderName.
2. Write a function placeBid(bidderName, bidAmount) that updates the
currentBid and bidderName if the new bid is higher than the existing bid.
3. Write a function getCurrentBid() that returns the highest bid and the name of
the highest bidder.
. Daily Budget Tracker
Scenario: You are building a personal finance tracker. The system should track expenses and
ensure they stay within the user's daily budget.
● Task:
1. Create an object budget with properties dailyLimit and expenses (an array).
2. Write a function addExpense(amount) that adds an expense to the expenses
array.
3. Write a function checkBudget() that checks if the total expenses for the day have
exceeded the dailyLimit.
. Simple Weather Forecast System
Scenario: You are building a weather forecast system where users can input the day of the week
and get the predicted temperature.
● Task:
1. Create an object forecast with properties for each day of the week, with
temperatures as values (e.g., "Monday": 22, "Tuesday": 19, etc.).
2. Write a function getForecast(day) that returns the temperature for the specified
day.
3. Write a function getAverageTemperature() that returns the average temperature
for the week.
. Simple To-Do List with Deadlines
Scenario: You are building a to-do list where users can add tasks and set deadlines for them.
● Task:
1. Create an array tasks where each task is an object with taskName, deadline,
and status properties.
2. Write a function addTask(taskName, deadline) that adds a new task to the list.
3. Write a function markTaskComplete(taskName) that sets the status of a task to
"completed".
4. Write a function getOverdueTasks() that returns an array of tasks that have
passed their deadline and are not completed.
. Simple Chat Application
Scenario: You are building a simple chat application where users can send messages to each
other.
● Task:
1. Create an array messages that stores objects with properties sender, message,
and timestamp.
2. Write a function sendMessage(sender, message) that adds a new message to
the messages array.
3. Write a function getMessages() that returns all messages in the chat, ordered by
timestamp.
. Task Prioritization System
Scenario: You are building a system that prioritizes tasks based on their importance and
urgency.
● Task:
1. Create an array tasks where each task is an object with taskName,
importanceLevel (1 to 5), and urgencyLevel (1 to 5).
2. Write a function addTask(taskName, importanceLevel, urgencyLevel) that
adds a task to the list.
3. Write a function getHighestPriorityTask() that returns the task with the
highest sum of importanceLevel and urgencyLevel.
. User Registration System
Scenario: You are building a user registration system where users can register with a username
and password.
● Task:
1. Create an array users where each user is an object with properties username and
password.
2. Write a function registerUser(username, password) that checks if the
username is already taken. If not, it adds the user to the list.
3. Write a function login(username, password) that checks if the credentials
match any user and returns a success message or error message.
. Inventory Management System
Scenario: You are building an inventory management system for a store. Each product has a
quantity and a price.
● Task:
1. Create an array inventory where each product is an object with name, quantity,
and price.
2. Write a function addProduct(name, quantity, price) that adds a new
product to the inventory.
3. Write a function updateQuantity(name, quantity) that updates the quantity of
an existing product.
4. Write a function getInventoryValue() that calculates and returns the total value
of the inventory.
. Simple Book Review System
Scenario: You are building a book review system where users can submit reviews for books they
have read.
● Task:
1. Create an array books where each book is an object with properties title,
author, and reviews (array of reviews).
2. Write a function addReview(title, review) that adds a review for a book.
3. Write a function getBookReviews(title) that returns all reviews for a specified
book.
4. Write a function getAverageRating(title) that calculates the average rating
for a book based on reviews.
Online Quiz with Timer
Scenario: You are building an online quiz system where users answer questions within a time
limit.
● Task:
1. Create an array questions where each question is an object with properties:
questionText, options, and correctAnswer.
2. Write a function startTimer(seconds) that starts a countdown timer for the
quiz.
3. Write a function answerQuestion(questionIndex, answer) that checks if the
provided answer is correct.
4. Write a function getScore() that returns the score based on correct answers.
. Expense Splitter
Scenario: You are building an expense splitter for a group of friends who went out for dinner.
● Task:
1. Create an array friends with the names of the people.
2. Write a function addExpense(amount) that splits the total amount evenly among
all friends.
3. Write a function getSharePerPerson() that returns the amount each person
should pay.
. Simple Voting Poll
Scenario: You are building a simple poll where users can vote for one option.
● Task:
1. Create an object poll with keys representing poll options (e.g., option1,
option2) and values representing the vote count.
2. Write a function voteForOption(option) that increases the vote count for the
specified option.
3. Write a function getMostVotedOption() that returns the option with the highest
vote count.
. Recipe Book System
Scenario: You are building a recipe book system where users can add and view recipes.
● Task:
1. Create an array recipes where each recipe is an object with name, ingredients,
and instructions.
2. Write a function addRecipe(name, ingredients, instructions) that adds a
new recipe.
3. Write a function getRecipe(name) that returns the recipe for the given name.
4. Write a function getAllRecipes() that returns a list of all recipe names.
. Password Strength Checker
Scenario: You are building a password strength checker for a registration system.
● Task:
1. Write a function checkPasswordStrength(password) that checks the password
against the following conditions:
▪ Minimum 8 characters long
▪ Contains at least one uppercase letter
▪ Contains at least one lowercase letter
▪ Contains at least one number
▪ Contains at least one special character (!@#$%^&*)
2. The function should return "Strong", "Medium", or "Weak" based on these
criteria.
. Recipe Ingredient Calculator
Scenario: You are building a system that calculates how much of each ingredient is needed for a
recipe based on the number of servings.
● Task:
1. Create an object recipe where each property is an ingredient and the value is the
amount required for one serving (e.g., { "flour": 1, "sugar": 0.5 }).
2. Write a function calculateIngredients(servings) that multiplies the
ingredient amounts by the number of servings.
. Simple Budget Planner
Scenario: You are building a simple budget planner where users can track their income and
expenses.
● Task:
1. Create an object budget with properties income and expenses (an array).
2. Write a function addIncome(amount) that adds to the total income.
3. Write a function addExpense(amount) that adds an expense to the expenses
array.
4. Write a function getRemainingBudget() that calculates and returns the
remaining budget.