🏠

🧮 JavaScript Console Practice Questions and Answers (ES5)

🌟 Objective: Practice JavaScript fundamentals with these console exercises. Each question provides a practical example of JavaScript in action. Read the instructions, write your code, and compare with the answer.

📑 Table of Contents

Variable Practice

Instructions: Create variables to store a student's name, age, and an array of grades. Print each value to the console with a label. Example output should look like:

// Student: John Doe
// Age: 18
// Grades: 85, 90, 78, 92
var studentName = "John Doe";
var studentAge = 18;
var studentGrades = [85, 90, 78, 92];

console.log("Student:", studentName);
console.log("Age:", studentAge);
console.log("Grades:", studentGrades.join(", "));

Type Conversion

Instructions: Demonstrate how JavaScript treats strings and numbers differently. Create two variables: one string ("5") and one number (2). Print the result of adding and subtracting them using console.log(). Explain why the results are different.

var num1 = "5";
var num2 = 2;

console.log("String + Number:", num1 + num2); // "52" (string)
console.log("String - Number:", num1 - num2); // 3 (number)

Temperature Converter

Instructions: Write code to convert temperatures between Celsius and Fahrenheit. First, convert 25°C to Fahrenheit and print the result. Then convert 77°F to Celsius and print the result. Use formulas:
°C = (°F - 32) × 5/9
°F = (°C × 9/5) + 32

var celsius = 25;
var fahrenheit = (celsius * 9 / 5) + 32;
console.log(celsius + "°C = " + fahrenheit + "°F");

fahrenheit = 77;
celsius = (fahrenheit - 32) * 5 / 9;
console.log(fahrenheit + "°F = " + celsius.toFixed(2) + "°C");

Simple Calculator

Instructions: Create a simple calculator using variables. Assign two numbers (a and b) and an operator ('+', '-', '*', or '/'). Use if/else to perform the operation and print the result to the console.

var a = 10;
var b = 5;
var operation = '*';
var result;

if (operation === '+') result = a + b;
else if (operation === '-') result = a - b;
else if (operation === '*') result = a * b;
else if (operation === '/') result = a / b;
else result = "Invalid operation";

console.log(a + " " + operation + " " + b + " = " + result);

Currency Converter

Instructions: Write a function that takes an amount in one currency and converts it to another using an exchange rate. Test the function by converting 100 USD to Euros at a rate of 0.91. Print the result.

function convertCurrency(amount, rate) {
  return (amount * rate).toFixed(2);
}

var usd = 100;
var rate = 0.91;
console.log(usd + " USD = €" + convertCurrency(usd, rate));

Grade Determiner

Instructions: Write a function that takes a student's score (number out of 100) and returns a grade based on these rules: 90+ = A, 80+ = B, 70+ = C, 60+ = D, below 60 = F. Test it with a score of 87 and print the result.

function getGrade(score) {
  if (score >= 90) return "A";
  if (score >= 80) return "B";
  if (score >= 70) return "C";
  if (score >= 60) return "D";
  return "F";
}

console.log("Grade:", getGrade(87));

Number Classifier

Instructions: Write a function that takes a number and prints whether it is positive, negative, or zero, and whether it is even or odd.

function classifyNumber(num) {
  var type = num > 0 ? "Positive" : num < 0 ? "Negative" : "Zero";
  var parity = num % 2 === 0 ? "Even" : "Odd";
  console.log(num + " is " + type + " and " + parity);
}

classifyNumber(-7);

Leap Year Checker

Instructions: Write a function that checks if a given year is a leap year. A year is a leap year if it is divisible by 4 but not by 100, unless it is also divisible by 400. Test your function with the year 2024 and print the result.

function isLeapYear(year) {
  if ((year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0)) {
    return true;
  }
  return false;
}

console.log("Leap Year?", isLeapYear(2024));

Student Marks Processor

Instructions: Given an array of marks, write code to find the total, average, highest, lowest marks, and count how many passed (mark ≥ 60). Print all these values to the console.

var marks = [78, 82, 93, 67, 55, 76, 89, 91, 68, 72];
var total = 0;
var highest = marks[0];
var lowest = marks[0];
var passed = 0;

for (var i = 0; i < marks.length; i++) {
  total += marks[i];
  if (marks[i] > highest) highest = marks[i];
  if (marks[i] < lowest) lowest = marks[i];
  if (marks[i] >= 60) passed++;
}

var average = total / marks.length;

console.log("Total:", total);
console.log("Average:", average.toFixed(2));
console.log("Highest:", highest);
console.log("Lowest:", lowest);
console.log("Passed:", passed);

Array Statistics

Instructions: Write a function that takes an array of numbers and returns the sum, average, maximum, and minimum values. Test it with the array [10, 20, 30, 40] and print the result.

function analyzeArray(arr) {
  var sum = 0;
  var max = arr[0];
  var min = arr[0];
  for (var i = 0; i < arr.length; i++) {
    sum += arr[i];
    if (arr[i] > max) max = arr[i];
    if (arr[i] < min) min = arr[i];
  }
  var avg = sum / arr.length;
  return { sum: sum, average: avg, max: max, min: min };
}

console.log(analyzeArray([10, 20, 30, 40]));

Shopping Cart Calculator

Instructions: Given an array of cart items (each with name, price, and quantity), print the total cost for each item and the overall subtotal, tax (5%), and final total.

var cart = [
  { item: "Laptop", price: 999.99, quantity: 1 },
  { item: "Headphones", price: 129.50, quantity: 2 },
  { item: "Mouse", price: 25.75, quantity: 1 }
];

var subtotal = 0;

for (var i = 0; i < cart.length; i++) {
  var total = cart[i].price * cart[i].quantity;
  subtotal += total;
  console.log(cart[i].item + " x" + cart[i].quantity + " = $" + total.toFixed(2));
}

var tax = subtotal * 0.05;
var finalTotal = subtotal + tax;

console.log("Subtotal:", subtotal.toFixed(2));
console.log("Tax:", tax.toFixed(2));
console.log("Total:", finalTotal.toFixed(2));

Array Transformation

Instructions: Write a function that takes an array and an operation ("square", "double", "half") and returns a new array after applying the operation to each element. Test with the array [1,2,3] and operation "square".

function transformArray(arr, operation) {
  var result = [];
  for (var i = 0; i < arr.length; i++) {
    if (operation === "square") result.push(arr[i] * arr[i]);
    else if (operation === "double") result.push(arr[i] * 2);
    else if (operation === "half") result.push(arr[i] / 2);
  }
  return result;
}

console.log(transformArray([1, 2, 3], "square"));

Student Records Manager

Instructions: Given an array of student objects (with id, name, and marks array), calculate and add total and average marks for each student. Print the top student (highest average) and print names of all students with average above 80.

var students = [
  { id: 1, name: "Ali", marks: [85, 90, 78] },
  { id: 2, name: "Fatima", marks: [92, 86, 93] },
  { id: 3, name: "Sara", marks: [70, 75, 80] }
];

for (var i = 0; i < students.length; i++) {
  var sum = 0;
  for (var j = 0; j < students[i].marks.length; j++) {
    sum += students[i].marks[j];
  }
  students[i].total = sum;
  students[i].average = sum / students[i].marks.length;
}

var topStudent = students[0];
for (var i = 1; i < students.length; i++) {
  if (students[i].average > topStudent.average) {
    topStudent = students[i];
  }
}

console.log("Top Student:", topStudent.name);

var threshold = 80;
for (var i = 0; i < students.length; i++) {
  if (students[i].average > threshold) {
    console.log("Above threshold:", students[i].name);
  }
}

Inventory Management System

Instructions: Create an inventory array of objects (with id, name, price, quantity). Write functions to add an item, update quantity, calculate total inventory value, and return items below a given stock threshold.

var inventory = [
  { id: 101, name: "Notebook", price: 12.99, quantity: 50 },
  { id: 102, name: "Pen Set", price: 7.50, quantity: 100 },
  { id: 103, name: "Stapler", price: 8.25, quantity: 30 }
];

function addItem(item) {
  inventory.push(item);
}

function updateQuantity(id, change) {
  for (var i = 0; i < inventory.length; i++) {
    if (inventory[i].id === id) {
      inventory[i].quantity += change;
    }
  }
}

function totalInventoryValue() {
  var total = 0;
  for (var i = 0; i < inventory.length; i++) {
    total += inventory[i].price * inventory[i].quantity;
  }
  return total;
}

function lowStock(threshold) {
  var result = [];
  for (var i = 0; i < inventory.length; i++) {
    if (inventory[i].quantity < threshold) {
      result.push(inventory[i]);
    }
  }
  return result;
}

Bank Account Simulator

Instructions: Create a bank account object with properties for owner, balance, and transactions. Write functions to deposit, withdraw, get the balance, and view transaction history. Print test results for each function.

var account = {
  owner: "Sara Ahmed",
  balance: 1000,
  transactions: []
};

function deposit(amount) {
  account.balance += amount;
  account.transactions.push({ type: "deposit", amount: amount });
}

function withdraw(amount) {
  if (amount > account.balance) {
    console.log("Insufficient funds");
    return;
  }
  account.balance -= amount;
  account.transactions.push({ type: "withdraw", amount: amount });
}

function getBalance() {
  return account.balance;
}

function getHistory() {
  return account.transactions;
}

To-Do List Manager

Instructions: Create a simple to-do list using an array of task objects. Write functions to add a new task, mark a task as complete, delete a task, and list all, completed, or pending tasks. Print sample outputs for each function.

var tasks = [
  { id: 1, description: "Complete assignment", completed: false },
  { id: 2, description: "Review notes", completed: true }
];

function addTask(desc) {
  tasks.push({ id: tasks.length + 1, description: desc, completed: false });
}

function markComplete(id) {
  for (var i = 0; i < tasks.length; i++) {
    if (tasks[i].id === id) {
      tasks[i].completed = true;
    }
  }
}

function deleteTask(id) {
  for (var i = 0; i < tasks.length; i++) {
    if (tasks[i].id === id) {
      tasks.splice(i, 1);
      break;
    }
  }
}

function listTasks(filter) {
  for (var i = 0; i < tasks.length; i++) {
    if (filter === "all" || (filter === "completed" && tasks[i].completed) || (filter === "pending" && !tasks[i].completed)) {
      console.log(tasks[i]);
    }
  }
}