To learn JavaScript but don't know where to begin

Want to learn JavaScript but don't know where to begin? This 30-day beginner-friendly roadmap takes you from zero to building a calculator and a final project. Every day includes a clear explanation, key topics, 5 code examples and a practice task, and the post ends with 7 complete mini projects in HTML, CSS and JavaScript. All you need is 45–60 minutes a day, a laptop, a browser and a code editor such as VS Code.

Quick overview
WeekDaysFocus
Week 11–7JavaScript basics
Week 28–14Programming fundamentals
Week 315–21JavaScript with HTML (DOM)
Week 422–30Advanced basics and final project
How to use this plan: Read the topic, type every example yourself (don't copy-paste), run it in the browser console or a .html file, change the values to see what happens, then finish the practice task. If you miss a day, continue from where you stopped instead of rushing.

Week 1: JavaScript Basics

Day 1: Introduction to JavaScript

Learn what JavaScript is, why it powers websites, apps and servers, and how it runs in the browser.

  • Set up VS Code and open the browser console (F12)
  • Use console.log() and write your first script
  • Link a .js file to an HTML page with <script>

Example 1: Your first output

console.log("Hello, World!");

Example 2: Printing text and numbers

console.log("My name is Asha");
console.log(2 + 3);   // 5

Example 3: Comments

// This is a single-line comment
/* This is a
   multi-line comment */
console.log("Comments are ignored by JavaScript");

Example 4: Pop-up alert

alert("Welcome to JavaScript!");

Example 5: Linking a script file (index.html)

<!DOCTYPE html>
<html>
<body>
  <h1>My first JS page</h1>
  <script src="script.js"></script>
</body>
</html>

// script.js
console.log("Script loaded!");

Practice: Print "Hello, World!" and your name to the console.

Day 2: Variables (let, const, var)

Variables store data. Understand the differences between the three ways to declare them.

  • let for values that change, const for values that don't
  • Why var is outdated and where it causes problems
  • Naming rules and camelCase convention

Example 1: Declaring with let

let name = "Asha";
console.log(name);   // Asha

Example 2: const cannot be reassigned

const PI = 3.14159;
console.log(PI);
// PI = 3;   // Error: Assignment to constant variable

Example 3: Changing a let value

let score = 10;
score = 20;
console.log(score);   // 20

Example 4: var leaks out of blocks

if (true) {
  var a = "I leak";
  let b = "I stay inside";
}
console.log(a);   // I leak
// console.log(b);   // Error: b is not defined

Example 5: Building a sentence

let city = "Delhi";
let age = 25;
console.log("I am " + age + " years old and live in " + city);

Practice: Store your name, age and city in variables and print a sentence using them.

Day 3: Data Types

Every value has a type. Knowing them prevents many beginner bugs.

  • String, Number, Boolean, Undefined, Null
  • Checking types with typeof
  • Type conversion, such as Number("5") and String(10)

Example 1: The main types

console.log(typeof "hello");   // string
console.log(typeof 42);        // number
console.log(typeof true);      // boolean

Example 2: Undefined and null

let x;
console.log(x);          // undefined
let y = null;
console.log(y);          // null

Example 3: Converting types

console.log(Number("5") + 1);   // 6
console.log(String(10) + 5);    // "105"
console.log(Boolean(0));        // false

Example 4: A common surprise

console.log("5" + 2);   // "52" (string joining)
console.log("5" - 2);   // 3   (math)

Example 5: Checking numbers

console.log(Number("abc"));         // NaN
console.log(isNaN("abc"));         // true
console.log(Number.isInteger(7));  // true

Practice: Create one variable of each type and print its type.

Day 4: Operators

Operators let you calculate and compare values.

  • Arithmetic: + - * / % **
  • Comparison: == === != !== > < (prefer ===)
  • Logical: && || ! and assignment operators like +=

Example 1: Arithmetic

console.log(10 + 3);   // 13
console.log(10 % 3);   // 1 (remainder)
console.log(2 ** 4);   // 16 (power)

Example 2: == vs ===

console.log(5 == "5");    // true  (loose)
console.log(5 === "5");   // false (strict, preferred)

Example 3: Logical operators

let age = 20, hasId = true;
console.log(age >= 18 && hasId);   // true
console.log(age < 18 || hasId);    // true
console.log(!hasId);               // false

Example 4: Assignment shortcuts

let n = 5;
n += 3;   // 8
n *= 2;   // 16
n++;      // 17
console.log(n);

Example 5: Area and even check

let width = 8, height = 5;
console.log("Area:", width * height);   // 40
let num = 14;
console.log(num % 2 === 0);            // true (even)

Practice: Write a program that calculates the area of a rectangle and checks if a number is even.

Day 5: Conditional Statements

Make your code take decisions.

  • if, else if, else
  • switch statements
  • The ternary operator condition ? a : b

Example 1: if / else

let age = 17;
if (age >= 18) {
  console.log("You can vote");
} else {
  console.log("Too young to vote");
}

Example 2: Grade calculator

let marks = 78;
if (marks >= 90) console.log("A");
else if (marks >= 75) console.log("B");
else if (marks >= 40) console.log("C");
else console.log("Fail");

Example 3: switch

let day = 3;
switch (day) {
  case 1: console.log("Monday"); break;
  case 2: console.log("Tuesday"); break;
  case 3: console.log("Wednesday"); break;
  default: console.log("Other day");
}

Example 4: Ternary operator

let num = 7;
let result = num % 2 === 0 ? "Even" : "Odd";
console.log(result);   // Odd

Example 5: Leap year check

let year = 2024;
if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
  console.log(year + " is a leap year");
} else {
  console.log(year + " is not a leap year");
}

Practice: Build a grade calculator (marks to A/B/C/Fail) and a program that prints the day name from a number.

Day 6: Loops

Repeat tasks without writing the same code again and again.

  • for, while and do...while
  • break and continue
  • Avoiding infinite loops

Example 1: for loop

for (let i = 1; i <= 5; i++) {
  console.log("Number " + i);
}

Example 2: while loop

let count = 3;
while (count > 0) {
  console.log(count);
  count--;
}

Example 3: do...while (runs at least once)

let i = 10;
do {
  console.log("i is " + i);
  i++;
} while (i < 5);

Example 4: break and continue

for (let i = 1; i <= 10; i++) {
  if (i === 3) continue;   // skip 3
  if (i === 6) break;      // stop at 6
  console.log(i);          // 1 2 4 5
}

Example 5: Table of 5 and sum 1 to 100

for (let i = 1; i <= 10; i++) {
  console.log("5 x " + i + " = " + 5 * i);
}
let sum = 0;
for (let n = 1; n <= 100; n++) sum += n;
console.log("Sum:", sum);   // 5050

Practice: Print a multiplication table, sum numbers from 1 to 100, and print a star pattern.

Day 7: Practice Programs

Revise Week 1 by combining everything you learned.

  • Even/odd checker, factorial, Fibonacci series
  • Prime number checker
  • Star patterns

Example 1: Even or odd

let n = 9;
console.log(n % 2 === 0 ? "Even" : "Odd");

Example 2: Factorial of 5

let fact = 1;
for (let i = 1; i <= 5; i++) fact *= i;
console.log(fact);   // 120

Example 3: Fibonacci (first 10)

let a = 0, b = 1;
for (let i = 0; i < 10; i++) {
  console.log(a);
  let next = a + b;
  a = b;
  b = next;
}

Example 4: Prime checker

let num = 29, isPrime = num > 1;
for (let i = 2; i < num; i++) {
  if (num % i === 0) { isPrime = false; break; }
}
console.log(num + (isPrime ? " is prime" : " is not prime"));

Example 5: Star pattern

for (let row = 1; row <= 5; row++) {
  console.log("*".repeat(row));
}
// *
// **
// ***
// ****
// *****

Practice: Solve at least 5 small problems without looking at notes.

Week 2: Programming Fundamentals

Day 8: Functions

Functions are reusable blocks of code and the heart of programming.

  • Declaring and calling functions
  • Parameters, arguments and the return value
  • Function expressions and default parameters

Example 1: A simple function

function greet() {
  console.log("Hello!");
}
greet();

Example 2: Parameters and return

function add(a, b) {
  return a + b;
}
console.log(add(4, 6));   // 10

Example 3: Default parameters

function welcome(name = "Guest") {
  return "Welcome, " + name;
}
console.log(welcome());         // Welcome, Guest
console.log(welcome("Asha"));   // Welcome, Asha

Example 4: Function expression

const square = function (n) {
  return n * n;
};
console.log(square(7));   // 49

Example 5: Temperature converter and max

function toFahrenheit(c) {
  return c * 9 / 5 + 32;
}
function max(a, b) {
  return a > b ? a : b;
}
console.log(toFahrenheit(100));   // 212
console.log(max(8, 15));          // 15

Practice: Write functions for add, subtract, a temperature converter and a maximum-of-two-numbers finder.

Day 9: Arrays

Arrays store lists of values in one variable.

  • Creating arrays and accessing items by index
  • push, pop, shift, unshift, length
  • Looping through arrays

Example 1: Create and access

let fruits = ["apple", "banana", "mango"];
console.log(fruits[0]);       // apple
console.log(fruits.length);   // 3

Example 2: push and pop (end of array)

fruits.push("orange");   // add at end
fruits.pop();            // remove last
console.log(fruits);

Example 3: unshift and shift (start of array)

fruits.unshift("kiwi");   // add at start
fruits.shift();           // remove first
console.log(fruits);

Example 4: Looping with for

let colors = ["red", "green", "blue"];
for (let i = 0; i < colors.length; i++) {
  console.log(i + ": " + colors[i]);
}

Example 5: for...of and indexOf

for (let color of colors) {
  console.log(color);
}
console.log(colors.indexOf("green"));   // 1

Practice: Create a list of 5 fruits, add and remove items, and print each one.

Day 10: Array Methods

Modern JavaScript relies heavily on array methods.

  • forEach, map, filter, reduce
  • find, includes, indexOf, sort, slice, splice

Example 1: forEach

let nums = [1, 2, 3, 4, 5];
nums.forEach(function (n) {
  console.log(n * 10);
});

Example 2: map (transform every item)

let doubled = nums.map(function (n) {
  return n * 2;
});
console.log(doubled);   // [2, 4, 6, 8, 10]

Example 3: filter (keep matching items)

let evens = nums.filter(function (n) {
  return n % 2 === 0;
});
console.log(evens);   // [2, 4]

Example 4: reduce (combine into one value)

let total = nums.reduce(function (sum, n) {
  return sum + n;
}, 0);
console.log(total);   // 15

Example 5: find, includes, sort, slice

console.log(nums.find(n => n > 3));    // 4
console.log(nums.includes(2));          // true
console.log([5, 1, 4].sort());          // [1, 4, 5]
console.log(nums.slice(1, 3));          // [2, 3]

Practice: From an array of numbers, double each value, keep only the even ones, and calculate the total.

Day 11: Objects

Objects store related data as key-value pairs.

  • Creating objects and accessing properties with dot and bracket notation
  • Adding, updating and deleting properties
  • Methods, the this keyword, Object.keys() and Object.values()

Example 1: Create and access

let student = { name: "Asha", age: 20, marks: 85 };
console.log(student.name);       // dot notation
console.log(student["marks"]);   // bracket notation

Example 2: Add, update, delete

student.city = "Delhi";   // add
student.age = 21;         // update
delete student.marks;     // delete
console.log(student);

Example 3: Methods and this

let person = {
  name: "Ravi",
  sayHi: function () {
    console.log("Hi, I am " + this.name);
  }
};
person.sayHi();

Example 4: keys, values, entries

let car = { brand: "Tata", year: 2022 };
console.log(Object.keys(car));     // ["brand", "year"]
console.log(Object.values(car));   // ["Tata", 2022]
console.log(Object.entries(car));

Example 5: Array of objects

let users = [
  { name: "Asha", age: 20 },
  { name: "Ravi", age: 25 }
];
users.forEach(u => console.log(u.name + " is " + u.age));

Practice: Create a student object with name, age and marks, plus a method that prints a summary.

Day 12: Strings

Text handling is needed in almost every project.

  • length, toUpperCase, toLowerCase, trim
  • slice, substring, replace, split, includes
  • Template literals with backticks

Example 1: Length and case

let text = "JavaScript";
console.log(text.length);          // 10
console.log(text.toUpperCase());   // JAVASCRIPT
console.log(text.toLowerCase());   // javascript

Example 2: trim and slice

console.log("  hello  ".trim());   // "hello"
console.log(text.slice(0, 4));      // Java
console.log(text.substring(4));     // Script

Example 3: replace and split

console.log("I like cats".replace("cats", "dogs"));
console.log("a,b,c".split(","));   // ["a", "b", "c"]

Example 4: Searching

console.log(text.includes("Script"));     // true
console.log(text.startsWith("Java"));     // true
console.log(text.indexOf("S"));           // 4

Example 5: Template literals and reverse

let name = "Asha", age = 20;
console.log(`${name} is ${age} years old`);
let word = "level";
let reversed = word.split("").reverse().join("");
console.log(word === reversed);   // true (palindrome)

Practice: Reverse a string, count vowels, and check whether a word is a palindrome.

Day 13: Scope

Scope decides where a variable can be used.

  • Global, function and block scope
  • Hoisting basics
  • Closures (a gentle introduction)

Example 1: Global scope

let site = "My Blog";
function show() {
  console.log(site);   // accessible here
}
show();

Example 2: Function scope

function test() {
  let secret = 123;
  console.log(secret);
}
test();
// console.log(secret);   // Error: not defined

Example 3: Block scope with let

if (true) {
  let inside = "block";
  console.log(inside);
}
// console.log(inside);   // Error: not defined

Example 4: Hoisting

console.log(a);   // undefined (var is hoisted)
var a = 5;
// console.log(b);   // Error (let is not usable before declaration)
// let b = 10;

Example 5: Closure counter

function makeCounter() {
  let count = 0;
  return function () {
    count++;
    return count;
  };
}
const counter = makeCounter();
console.log(counter());   // 1
console.log(counter());   // 2

Practice: Predict the output of small snippets, then run them to check yourself.

Day 14: Practice Projects

Time to build small things with Weeks 1 and 2 combined.

  • Tip calculator
  • Simple to-do list stored in an array
  • Student marks and average calculator

Example 1: Tip calculator

function calcTip(bill, percent) {
  return bill * percent / 100;
}
let bill = 1200;
console.log("Tip:", calcTip(bill, 10));                 // 120
console.log("Total:", bill + calcTip(bill, 10));        // 1320

Example 2: To-do list in an array

let todos = [];
function addTodo(task) { todos.push(task); }
function removeTodo(index) { todos.splice(index, 1); }
addTodo("Learn JS");
addTodo("Practice loops");
removeTodo(0);
console.log(todos);   // ["Practice loops"]

Example 3: Average marks

let marks = [78, 85, 92, 66, 74];
let total = marks.reduce((s, m) => s + m, 0);
console.log("Average:", total / marks.length);

Example 4: Shopping cart total

let cart = [
  { item: "Pen", price: 10, qty: 5 },
  { item: "Book", price: 150, qty: 2 }
];
let sum = 0;
for (let c of cart) sum += c.price * c.qty;
console.log("Cart total:", sum);   // 350

Example 5: Password strength checker

function checkPassword(pw) {
  if (pw.length < 6) return "Weak";
  if (pw.length < 10) return "Medium";
  return "Strong";
}
console.log(checkPassword("abc123"));        // Medium
console.log(checkPassword("MyS3cretPass!")); // Strong

Practice: Finish at least two of the three projects.

Week 3: JavaScript with HTML

Day 15: Introduction to the DOM

The DOM (Document Object Model) is how JavaScript sees and controls a web page.

  • The page as a tree of elements
  • document and window objects

Example 1: A page to experiment with (index.html)

<h1 id="title">Hello DOM</h1>
<ul id="list">
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>
<script src="script.js"></script>

Example 2: The document object

console.log(document.title);
console.log(document.body);
console.log(document.URL);

Example 3: Reading the page tree

let list = document.getElementById("list");
console.log(list.children);          // all <li> items
console.log(list.children.length);   // 3

Example 4: Moving through the tree

let first = list.firstElementChild;
console.log(first.textContent);                    // One
console.log(first.nextElementSibling.textContent); // Two
console.log(first.parentElement.id);               // list

Example 5: The window object

console.log(window.innerWidth);
console.log(window.location.href);
console.log(window.innerHeight);

Practice: Create a basic HTML page and inspect its structure in the browser's Elements tab.

Day 16: Selecting HTML Elements

You must select an element before you can change it.

  • getElementById, querySelector, querySelectorAll
  • Selecting by class and tag name

Example 1: HTML used below

<h1 id="main">Title</h1>
<p class="note">First note</p>
<p class="note">Second note</p>

Example 2: By id

let heading = document.getElementById("main");
console.log(heading.textContent);

Example 3: querySelector (first match)

let firstNote = document.querySelector(".note");
console.log(firstNote.textContent);   // First note

Example 4: querySelectorAll (all matches)

let notes = document.querySelectorAll(".note");
notes.forEach(function (n) {
  console.log(n.textContent);
});

Example 5: By class and tag name

console.log(document.getElementsByClassName("note").length);   // 2
console.log(document.getElementsByTagName("p").length);        // 2

Practice: Select a heading, a paragraph and a list of items, and log them in the console.

Day 17: Events and Event Listeners

Events make pages interactive.

  • click, input, submit, keydown, mouseover
  • addEventListener and the event object

Example 1: Click event

<button id="btn">Click me</button>
<script>
  document.getElementById("btn").addEventListener("click", function () {
    alert("Button clicked!");
  });
</script>

Example 2: Click counter

<button id="count">0</button>
<script>
  let n = 0;
  const btn = document.getElementById("count");
  btn.addEventListener("click", function () {
    n++;
    btn.textContent = n;
  });
</script>

Example 3: Input event (live typing)

<input id="name" placeholder="Type here">
<p id="out"></p>
<script>
  document.getElementById("name").addEventListener("input", function (e) {
    document.getElementById("out").textContent = e.target.value;
  });
</script>

Example 4: Keyboard event

document.addEventListener("keydown", function (e) {
  console.log("You pressed:", e.key);
});

Example 5: Mouse events

const box = document.getElementById("box");
box.addEventListener("mouseover", () => box.style.background = "orange");
box.addEventListener("mouseout",  () => box.style.background = "lightgray");

Practice: Make a button that shows an alert and a counter that increases on every click.

Day 18: Changing HTML Content

Update the page without reloading it.

  • textContent, innerHTML
  • Creating elements with createElement and adding them with appendChild
  • Removing elements

Example 1: textContent

document.getElementById("title").textContent = "New Title";

Example 2: innerHTML (can contain HTML tags)

document.getElementById("box").innerHTML = "<b>Bold</b> and <i>italic</i>";

Example 3: Create and add an element

let li = document.createElement("li");
li.textContent = "New item";
document.getElementById("list").appendChild(li);

Example 4: Remove an element

let item = document.querySelector("#list li");
item.remove();

Example 5: Add-item list

<input id="task" placeholder="New task">
<button id="add">Add</button>
<ul id="tasks"></ul>
<script>
  document.getElementById("add").addEventListener("click", function () {
    let input = document.getElementById("task");
    if (input.value.trim() === "") return;
    let li = document.createElement("li");
    li.textContent = input.value;
    document.getElementById("tasks").appendChild(li);
    input.value = "";
  });
</script>

Practice: Build a list where you type an item and add it to the page.

Day 19: CSS Manipulation

Change styles using JavaScript.

  • element.style properties
  • classList.add, remove and toggle

Example 1: Change inline style

let box = document.getElementById("box");
box.style.backgroundColor = "tomato";
box.style.fontSize = "24px";

Example 2: Add a CSS class

/* CSS */
.highlight { background: yellow; font-weight: bold; }

// JavaScript
document.getElementById("box").classList.add("highlight");

Example 3: Dark mode toggle

/* CSS */
.dark { background: #111; color: #fff; }

// JavaScript
document.getElementById("theme").addEventListener("click", function () {
  document.body.classList.toggle("dark");
});

Example 4: Remove a class and check for one

let el = document.getElementById("box");
el.classList.remove("highlight");
console.log(el.classList.contains("highlight"));   // false

Example 5: Show and hide an element

let panel = document.getElementById("panel");
document.getElementById("toggle").addEventListener("click", function () {
  panel.style.display = panel.style.display === "none" ? "block" : "none";
});

Practice: Create a dark mode toggle button and a box that changes colour on hover or click.

Day 20: Forms and Validation

Check user input before accepting it.

  • Reading input values and handling the submit event
  • event.preventDefault()
  • Showing error messages for empty fields, email format and password length

Example 1: Reading an input value

<input id="username">
<button id="show">Show</button>
<script>
  document.getElementById("show").addEventListener("click", function () {
    alert(document.getElementById("username").value);
  });
</script>

Example 2: Handling form submit

<form id="form">
  <input id="email" placeholder="Email">
  <button type="submit">Send</button>
</form>
<script>
  document.getElementById("form").addEventListener("submit", function (e) {
    e.preventDefault();   // stop page reload
    console.log("Form submitted");
  });
</script>

Example 3: Empty field check

let name = document.getElementById("name").value.trim();
if (name === "") {
  document.getElementById("error").textContent = "Name is required";
}

Example 4: Email check

let email = "asha@example.com";
let valid = email.includes("@") && email.includes(".");
console.log(valid ? "Valid email" : "Invalid email");
// Stronger check with a regular expression:
console.log(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email));

Example 5: Password length check

let password = document.getElementById("pw").value;
let msg = document.getElementById("pwMsg");
if (password.length < 8) {
  msg.textContent = "Password must be at least 8 characters";
  msg.style.color = "red";
} else {
  msg.textContent = "Looks good!";
  msg.style.color = "green";
}

Practice: Build a signup form with name, email and password validation.

Day 21: Build a Calculator

Your first real project, bringing the whole week together.

  • HTML buttons and display, CSS grid layout
  • JavaScript for button clicks, calculation and clear/delete

Example 1: HTML layout

<input id="display" readonly>
<div id="keys">
  <button>7</button><button>8</button><button>9</button><button>/</button>
  <button>4</button><button>5</button><button>6</button><button>*</button>
  <button>1</button><button>2</button><button>3</button><button>-</button>
  <button>0</button><button>.</button><button id="eq">=</button><button>+</button>
  <button id="clear">C</button>
</div>

Example 2: CSS grid for the keys

#keys { display: grid; grid-template-columns: repeat(4, 60px); gap: 6px; }
#keys button { height: 50px; font-size: 20px; }
#display { width: 100%; font-size: 28px; text-align: right; }

Example 3: Type numbers into the display

const display = document.getElementById("display");
document.querySelectorAll("#keys button").forEach(function (b) {
  b.addEventListener("click", function () {
    if (b.id === "eq" || b.id === "clear") return;
    display.value += b.textContent;
  });
});

Example 4: Clear and delete last character

document.getElementById("clear").addEventListener("click", function () {
  display.value = "";
});
// Delete last character:
display.value = display.value.slice(0, -1);

Example 5: Calculate the result safely

function calculate(expr) {
  const m = expr.match(/^(-?\d*\.?\d+)([+\-*\/])(-?\d*\.?\d+)$/);
  if (!m) return "Error";
  const a = parseFloat(m[1]), op = m[2], b = parseFloat(m[3]);
  if (op === "+") return a + b;
  if (op === "-") return a - b;
  if (op === "*") return a * b;
  if (op === "/") return b === 0 ? "Cannot divide by 0" : a / b;
}
document.getElementById("eq").addEventListener("click", function () {
  display.value = calculate(display.value);
});

Practice: Complete a working calculator with + - × ÷ and a clear button.

Week 4: Advanced Basics

Day 22: ES6 Features

Modern JavaScript syntax that makes code shorter and cleaner.

  • Template literals, destructuring, spread and rest operators
  • Default parameters and modules (import/export)

Example 1: Array destructuring

const [a, b, c] = [10, 20, 30];
console.log(a, b, c);   // 10 20 30

Example 2: Object destructuring

const user = { name: "Asha", age: 20, city: "Delhi" };
const { name, city } = user;
console.log(name, city);

Example 3: Spread operator

const nums = [1, 2, 3];
const more = [...nums, 4, 5];
console.log(more);   // [1, 2, 3, 4, 5]
const updated = { ...user, age: 21 };   // copy an object and change one value

Example 4: Rest parameters

function sumAll(...numbers) {
  return numbers.reduce((s, n) => s + n, 0);
}
console.log(sumAll(1, 2, 3, 4));   // 10

Example 5: Modules (import / export)

// math.js
export function add(a, b) { return a + b; }
export const PI = 3.14;

// main.js
import { add, PI } from "./math.js";
console.log(add(2, 3), PI);

// In HTML: <script type="module" src="main.js"></script>

Practice: Rewrite an old program using destructuring and the spread operator.

Day 23: Arrow Functions

A shorter way to write functions.

  • Syntax: const add = (a, b) => a + b
  • Implicit return and how this behaves differently
  • Using arrow functions with map and filter

Example 1: Basic arrow function

const add = (a, b) => {
  return a + b;
};
console.log(add(2, 3));   // 5

Example 2: Implicit return (one-liner)

const square = n => n * n;
const greet = () => "Hello!";
console.log(square(6), greet());

Example 3: Returning an object

const makeUser = (name, age) => ({ name, age });
console.log(makeUser("Asha", 20));

Example 4: With map and filter

const nums = [1, 2, 3, 4, 5, 6];
console.log(nums.map(n => n * 2));         // [2, 4, 6, 8, 10, 12]
console.log(nums.filter(n => n % 2 === 0)); // [2, 4, 6]

Example 5: Arrow functions and this

const timer = {
  seconds: 0,
  start() {
    setInterval(() => {
      this.seconds++;        // "this" still points to timer
      console.log(this.seconds);
    }, 1000);
  }
};
timer.start();

Practice: Convert five of your earlier functions into arrow functions.

Day 24: JSON

JSON is the standard format for exchanging data between apps and servers.

  • JSON syntax rules
  • JSON.stringify() and JSON.parse()
  • Saving data in localStorage

Example 1: Object to JSON text

const user = { name: "Asha", age: 20 };
const text = JSON.stringify(user);
console.log(text);          // {"name":"Asha","age":20}
console.log(typeof text);   // string

Example 2: JSON text to object

const json = '{"name":"Ravi","age":25}';
const obj = JSON.parse(json);
console.log(obj.name);   // Ravi

Example 3: Arrays in JSON

const list = ["html", "css", "js"];
const saved = JSON.stringify(list);
console.log(JSON.parse(saved)[2]);   // js

Example 4: localStorage basics

localStorage.setItem("theme", "dark");
console.log(localStorage.getItem("theme"));   // dark
localStorage.removeItem("theme");

Example 5: Save and load a to-do list

let todos = ["Learn JSON", "Build project"];
localStorage.setItem("todos", JSON.stringify(todos));

let loaded = JSON.parse(localStorage.getItem("todos")) || [];
console.log(loaded);

Practice: Save your to-do list in localStorage so it stays after refreshing.

Day 25: Promises

Handle tasks that take time, such as loading data.

  • Pending, fulfilled and rejected states
  • .then(), .catch(), .finally()
  • setTimeout and Promise.all

Example 1: setTimeout basics

setTimeout(function () {
  console.log("Runs after 2 seconds");
}, 2000);

Example 2: Creating a promise

const promise = new Promise(function (resolve, reject) {
  const ok = true;
  if (ok) resolve("Success!");
  else reject("Something failed");
});

Example 3: then, catch, finally

promise
  .then(result => console.log(result))
  .catch(error => console.log("Error:", error))
  .finally(() => console.log("Done"));

Example 4: Chaining promises

Promise.resolve(5)
  .then(n => n * 2)
  .then(n => n + 1)
  .then(n => console.log(n));   // 11

Example 5: Promise.all

const p1 = new Promise(res => setTimeout(() => res("A"), 1000));
const p2 = new Promise(res => setTimeout(() => res("B"), 2000));
Promise.all([p1, p2]).then(values => console.log(values));   // ["A", "B"]

Practice: Create a promise that resolves after 2 seconds and handle both success and failure.

Day 26: Async and Await

A cleaner way to work with promises.

  • The async keyword and await
  • Writing asynchronous code that reads like normal code

Example 1: Basic async function

async function hello() {
  return "Hello from async";
}
hello().then(console.log);

Example 2: Waiting with await

const wait = ms => new Promise(res => setTimeout(res, ms));

async function run() {
  console.log("Start");
  await wait(2000);
  console.log("2 seconds later");
}
run();

Example 3: try / catch with await

async function load() {
  try {
    const result = await Promise.reject("Network down");
  } catch (err) {
    console.log("Caught:", err);
  }
}
load();

Example 4: One after another vs together

async function demo() {
  // One after another (about 2 seconds)
  await wait(1000);
  await wait(1000);

  // Together (about 1 second)
  await Promise.all([wait(1000), wait(1000)]);
}

Example 5: Async arrow function

const getNumber = async () => 42;

(async () => {
  const n = await getNumber();
  console.log(n);   // 42
})();

Practice: Rewrite yesterday's promise examples using async/await.

Day 27: Fetch API

Get real data from the internet.

  • fetch(url) and response.json()
  • GET and POST requests
  • Displaying API data on a page

Example 1: Fetch with then

fetch("https://jsonplaceholder.typicode.com/users")
  .then(res => res.json())
  .then(data => console.log(data));

Example 2: Fetch with async/await

async function getUsers() {
  const res = await fetch("https://jsonplaceholder.typicode.com/users");
  const users = await res.json();
  console.log(users[0].name);
}
getUsers();

Example 3: Show data on the page

<ul id="users"></ul>
<script>
  async function showUsers() {
    const res = await fetch("https://jsonplaceholder.typicode.com/users");
    const users = await res.json();
    users.forEach(u => {
      const li = document.createElement("li");
      li.textContent = u.name + " (" + u.email + ")";
      document.getElementById("users").appendChild(li);
    });
  }
  showUsers();
</script>

Example 4: POST request

fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ title: "Hello", body: "My first post", userId: 1 })
})
  .then(res => res.json())
  .then(data => console.log(data));

Example 5: Check the response status

async function getPost(id) {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts/" + id);
  console.log(res.status, res.ok);   // 200 true
  return res.json();
}
getPost(1).then(console.log);

Practice: Fetch a list of users from a free API such as JSONPlaceholder and show them as cards.

Day 28: Error Handling

Make your programs reliable.

  • try...catch...finally and throw
  • Handling failed network requests
  • Reading console error messages and debugging with breakpoints

Example 1: try / catch

try {
  let x = JSON.parse("not valid json");
} catch (error) {
  console.log("Oops:", error.message);
}

Example 2: finally always runs

try {
  console.log("Trying...");
  nonExistentFunction();
} catch (e) {
  console.log("Error caught");
} finally {
  console.log("Cleanup done");
}

Example 3: Throwing your own error

function divide(a, b) {
  if (b === 0) throw new Error("Cannot divide by zero");
  return a / b;
}
try {
  divide(10, 0);
} catch (e) {
  console.log(e.message);
}

Example 4: Safe JSON parsing

function safeParse(text) {
  try {
    return JSON.parse(text);
  } catch {
    return null;
  }
}
console.log(safeParse('{"a":1}'));   // { a: 1 }
console.log(safeParse("oops"));      // null

Example 5: Handling fetch errors

async function loadData() {
  try {
    const res = await fetch("https://jsonplaceholder.typicode.com/posts/9999");
    if (!res.ok) throw new Error("Server error: " + res.status);
    console.log(await res.json());
  } catch (err) {
    document.getElementById("msg").textContent = "Something went wrong";
    console.log(err.message);
  }
}
loadData();

Practice: Add error handling and a "Something went wrong" message to your fetch project.

Days 29–30: Final Project

Combine everything into one project you can show others. Pick one idea (weather app, to-do app, quiz app, or user/movie search) and use the building blocks below. The examples show a user search app built step by step.

  • Weather app: search a city and show live weather using an API
  • To-do app: add, delete, complete tasks and save in localStorage
  • Quiz app: questions, score, and a result screen
  • User or movie search: fetch data from an API with search and error handling

Example 1: Step 1: Page skeleton

<h1>User Finder</h1>
<input id="search" placeholder="Search by name">
<p id="status"></p>
<div id="cards"></div>
<script src="app.js"></script>

Example 2: Step 2: Fetch the data with error handling

let users = [];

async function loadUsers() {
  const status = document.getElementById("status");
  status.textContent = "Loading...";
  try {
    const res = await fetch("https://jsonplaceholder.typicode.com/users");
    if (!res.ok) throw new Error("Request failed");
    users = await res.json();
    status.textContent = "";
    render(users);
  } catch (err) {
    status.textContent = "Something went wrong. Please try again.";
  }
}
loadUsers();

Example 3: Step 3: Show the data as cards

function render(list) {
  const box = document.getElementById("cards");
  box.innerHTML = "";
  list.forEach(u => {
    const card = document.createElement("div");
    card.className = "card";
    card.innerHTML = `<h3>${u.name}</h3><p>${u.email}</p><p>${u.company.name}</p>`;
    box.appendChild(card);
  });
}

Example 4: Step 4: Live search filter

document.getElementById("search").addEventListener("input", function (e) {
  const term = e.target.value.toLowerCase();
  const filtered = users.filter(u => u.name.toLowerCase().includes(term));
  render(filtered);
});

Example 5: Step 5: Save favourites in localStorage

let favs = JSON.parse(localStorage.getItem("favs")) || [];

function toggleFav(id) {
  favs = favs.includes(id) ? favs.filter(f => f !== id) : [...favs, id];
  localStorage.setItem("favs", JSON.stringify(favs));
}
// Call toggleFav(u.id) from a "Favourite" button inside each card.

Practice: Use the DOM, events, functions, arrays/objects, JSON, fetch and error handling together, then upload the finished project to GitHub.

Mini Projects (HTML + CSS + JavaScript)

How to run these projects: Create a new folder for each project, then make three files inside it: index.html, style.css and script.js. Paste in the code, save, and double-click index.html to open it in your browser. Build them after the day shown in brackets, type the code yourself, then try the challenge at the end of each project.

Mini Project 1: Click Counter (after Day 17)

A counter with plus, minus and reset buttons. Practices selecting elements, click events and updating text.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Click Counter</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="card">
    <h1>Click Counter</h1>
    <p id="count">0</p>
    <div class="buttons">
      <button id="minus">-</button>
      <button id="reset">Reset</button>
      <button id="plus">+</button>
    </div>
  </div>
  <script src="script.js"></script>
</body>
</html>

style.css

body {
  font-family: Arial, sans-serif;
  background: #f0f4f8;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  margin: 0;
}
.card {
  background: #fff;
  padding: 30px 40px;
  border-radius: 12px;
  text-align: center;
  box-shadow: 0 4px 14px rgba(0, 0, 0, 0.12);
}
#count { font-size: 64px; margin: 10px 0 20px; }
.buttons button {
  font-size: 20px;
  padding: 10px 18px;
  margin: 0 4px;
  border: none;
  border-radius: 8px;
  background: #1a56a0;
  color: #fff;
  cursor: pointer;
}
.buttons button:hover { background: #12407a; }

script.js

let count = 0;
const countEl = document.getElementById("count");

function update() {
  countEl.textContent = count;
  countEl.style.color = count < 0 ? "red" : count > 0 ? "green" : "black";
}

document.getElementById("plus").addEventListener("click", function () {
  count++;
  update();
});
document.getElementById("minus").addEventListener("click", function () {
  count--;
  update();
});
document.getElementById("reset").addEventListener("click", function () {
  count = 0;
  update();
});

Challenge: Add a step size input so the buttons add or subtract any number you choose.

Mini Project 2: Digital Clock (after Day 18)

A live clock and date that update every second. Practices functions, the Date object, setInterval and changing page content.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Digital Clock</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="clock">
    <div id="time">00:00:00</div>
    <div id="date"></div>
  </div>
  <script src="script.js"></script>
</body>
</html>

style.css

body {
  background: #111;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  margin: 0;
  font-family: "Courier New", monospace;
}
.clock { text-align: center; color: #39ff14; }
#time {
  font-size: 72px;
  letter-spacing: 4px;
  text-shadow: 0 0 12px #39ff14;
}
#date { font-size: 20px; margin-top: 10px; color: #9be28f; }
@media (max-width: 500px) { #time { font-size: 44px; } }

script.js

const timeEl = document.getElementById("time");
const dateEl = document.getElementById("date");

function tick() {
  const now = new Date();
  timeEl.textContent = now.toLocaleTimeString();
  dateEl.textContent = now.toLocaleDateString(undefined, {
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric"
  });
}

tick();                  // show immediately
setInterval(tick, 1000); // then update every second

Challenge: Add a button to switch between 12-hour and 24-hour time.

Mini Project 3: Dark Mode Toggle (after Day 19)

A page that switches between light and dark themes and remembers your choice. Practices classList.toggle and localStorage.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Dark Mode Toggle</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="card">
    <h1>Hello, JavaScript!</h1>
    <p>Click the button to switch between light and dark mode. Refresh the page and your choice is remembered.</p>
    <button id="themeBtn">Switch to dark mode</button>
  </div>
  <script src="script.js"></script>
</body>
</html>

style.css

body {
  font-family: Arial, sans-serif;
  background: #f5f5f5;
  color: #222;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  margin: 0;
  transition: background 0.3s, color 0.3s;
}
body.dark { background: #121212; color: #eee; }
.card {
  max-width: 380px;
  padding: 28px;
  border-radius: 12px;
  background: rgba(128, 128, 128, 0.15);
  text-align: center;
}
button {
  padding: 10px 18px;
  font-size: 16px;
  border: none;
  border-radius: 8px;
  background: #f5a623;
  cursor: pointer;
}

script.js

const btn = document.getElementById("themeBtn");

function applyTheme(isDark) {
  document.body.classList.toggle("dark", isDark);
  btn.textContent = isDark ? "Switch to light mode" : "Switch to dark mode";
}

// Load the saved choice
applyTheme(localStorage.getItem("theme") === "dark");

btn.addEventListener("click", function () {
  const isDark = !document.body.classList.contains("dark");
  applyTheme(isDark);
  localStorage.setItem("theme", isDark ? "dark" : "light");
});

Challenge: Add a third theme (for example blue) and cycle through all three.

Mini Project 4: Signup Form with Validation (after Day 20)

A signup form that checks name, email and passwords and shows friendly error messages. Practices the submit event, preventDefault and validation.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Signup Form</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <form id="signup" novalidate>
    <h1>Create Account</h1>

    <label for="name">Name</label>
    <input id="name" type="text" placeholder="Your name">
    <small class="error" id="nameError"></small>

    <label for="email">Email</label>
    <input id="email" type="email" placeholder="you@example.com">
    <small class="error" id="emailError"></small>

    <label for="password">Password</label>
    <input id="password" type="password" placeholder="At least 8 characters">
    <small class="error" id="passwordError"></small>

    <label for="confirm">Confirm password</label>
    <input id="confirm" type="password" placeholder="Repeat password">
    <small class="error" id="confirmError"></small>

    <button type="submit">Sign up</button>
    <p id="success"></p>
  </form>
  <script src="script.js"></script>
</body>
</html>

style.css

body {
  font-family: Arial, sans-serif;
  background: #eef2f7;
  display: flex;
  justify-content: center;
  padding: 30px 16px;
  margin: 0;
}
form {
  background: #fff;
  width: 100%;
  max-width: 360px;
  padding: 26px;
  border-radius: 12px;
  box-shadow: 0 4px 14px rgba(0, 0, 0, 0.12);
}
h1 { margin-top: 0; text-align: center; font-size: 24px; }
label { display: block; margin-top: 14px; font-weight: bold; font-size: 14px; }
input {
  width: 100%;
  box-sizing: border-box;
  padding: 10px;
  margin-top: 4px;
  border: 2px solid #ccc;
  border-radius: 6px;
  font-size: 15px;
}
input.invalid { border-color: #d32f2f; }
input.valid { border-color: #2e7d32; }
.error { color: #d32f2f; display: block; min-height: 16px; }
button {
  width: 100%;
  margin-top: 18px;
  padding: 12px;
  border: none;
  border-radius: 8px;
  background: #1a56a0;
  color: #fff;
  font-size: 16px;
  cursor: pointer;
}
#success { color: #2e7d32; text-align: center; font-weight: bold; }

script.js

const form = document.getElementById("signup");

function setError(id, message) {
  const input = document.getElementById(id);
  document.getElementById(id + "Error").textContent = message;
  input.classList.toggle("invalid", message !== "");
  input.classList.toggle("valid", message === "");
  return message === "";
}

form.addEventListener("submit", function (e) {
  e.preventDefault(); // stop the page from reloading

  const name = document.getElementById("name").value.trim();
  const email = document.getElementById("email").value.trim();
  const password = document.getElementById("password").value;
  const confirm = document.getElementById("confirm").value;

  const okName = setError("name", name.length < 2 ? "Enter at least 2 characters" : "");
  const okEmail = setError("email", /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) ? "" : "Enter a valid email");
  const okPass = setError("password", password.length < 8 ? "Password must be at least 8 characters" : "");
  const okConfirm = setError("confirm", confirm !== password || confirm === "" ? "Passwords do not match" : "");

  const success = document.getElementById("success");
  if (okName && okEmail && okPass && okConfirm) {
    success.textContent = "Account created for " + name + "!";
    form.reset();
    document.querySelectorAll("input").forEach(i => i.classList.remove("valid"));
  } else {
    success.textContent = "";
  }
});

Challenge: Show a password strength message (weak, medium, strong) while the user types.

Mini Project 5: Calculator (after Day 21)

A working calculator with + - × ÷, decimals, clear and delete. Practices the DOM, events, CSS grid and functions together.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Calculator</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="calc">
    <div class="screen">
      <div id="history"></div>
      <div id="display">0</div>
    </div>
    <div class="keys">
      <button data-action="clear" class="fn">C</button>
      <button data-action="delete" class="fn">DEL</button>
      <button data-op="/" class="op">÷</button>
      <button data-op="*" class="op">×</button>

      <button data-num="7">7</button>
      <button data-num="8">8</button>
      <button data-num="9">9</button>
      <button data-op="-" class="op">−</button>

      <button data-num="4">4</button>
      <button data-num="5">5</button>
      <button data-num="6">6</button>
      <button data-op="+" class="op">+</button>

      <button data-num="1">1</button>
      <button data-num="2">2</button>
      <button data-num="3">3</button>
      <button data-action="equals" class="eq">=</button>

      <button data-num="0" class="zero">0</button>
      <button data-num=".">.</button>
    </div>
  </div>
  <script src="script.js"></script>
</body>
</html>

style.css

body {
  font-family: Arial, sans-serif;
  background: #263238;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  margin: 0;
}
.calc {
  background: #37474f;
  padding: 16px;
  border-radius: 14px;
  width: 300px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
}
.screen {
  background: #1c2529;
  color: #fff;
  text-align: right;
  padding: 12px;
  border-radius: 8px;
  margin-bottom: 12px;
  overflow: hidden;
}
#history { min-height: 18px; font-size: 14px; color: #90a4ae; }
#display { font-size: 34px; word-wrap: break-word; }
.keys { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }
.keys button {
  height: 54px;
  font-size: 20px;
  border: none;
  border-radius: 8px;
  background: #546e7a;
  color: #fff;
  cursor: pointer;
}
.keys button:hover { filter: brightness(1.15); }
.keys .op { background: #f5a623; }
.keys .fn { background: #78909c; }
.keys .eq { background: #43a047; grid-row: span 2; height: auto; }
.keys .zero { grid-column: span 2; }

script.js

const displayEl = document.getElementById("display");
const historyEl = document.getElementById("history");

let current = "0";    // number being typed
let previous = null;  // first number
let operator = null;  // + - * /
let justCalculated = false;

const symbols = { "+": "+", "-": "−", "*": "×", "/": "÷" };

function updateScreen() {
  displayEl.textContent = current;
  historyEl.textContent = previous !== null && operator
    ? previous + " " + symbols[operator]
    : "";
}

function inputNumber(n) {
  if (justCalculated) { current = "0"; justCalculated = false; }
  if (n === "." && current.includes(".")) return;
  current = current === "0" && n !== "." ? n : current + n;
}

function calculate(a, b, op) {
  a = parseFloat(a);
  b = parseFloat(b);
  let result;
  if (op === "+") result = a + b;
  if (op === "-") result = a - b;
  if (op === "*") result = a * b;
  if (op === "/") result = b === 0 ? "Cannot divide by 0" : a / b;
  return typeof result === "number" ? String(+result.toFixed(10)) : result;
}

function chooseOperator(op) {
  if (isNaN(parseFloat(current))) return;
  if (operator && !justCalculated) {
    current = calculate(previous, current, operator);
    if (isNaN(parseFloat(current))) { previous = null; operator = null; return; }
  }
  previous = current;
  operator = op;
  current = "0";
  justCalculated = false;
}

function equals() {
  if (operator === null || previous === null) return;
  current = calculate(previous, current, operator);
  previous = null;
  operator = null;
  justCalculated = true;
}

document.querySelector(".keys").addEventListener("click", function (e) {
  const btn = e.target.closest("button");
  if (!btn) return;

  if (btn.dataset.num !== undefined) inputNumber(btn.dataset.num);
  else if (btn.dataset.op) chooseOperator(btn.dataset.op);
  else if (btn.dataset.action === "equals") equals();
  else if (btn.dataset.action === "clear") {
    current = "0"; previous = null; operator = null; justCalculated = false;
  } else if (btn.dataset.action === "delete") {
    current = current.length > 1 ? current.slice(0, -1) : "0";
  }
  updateScreen();
});

updateScreen();

Challenge: Add keyboard support so number keys, Enter and Backspace work.

Mini Project 6: To-Do List with Saving (after Day 24)

Add, complete and delete tasks, and keep them after refreshing the page. Practices arrays of objects, DOM creation, JSON and localStorage.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>To-Do List</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="app">
    <h1>My To-Do List</h1>
    <form id="todoForm">
      <input id="todoInput" type="text" placeholder="Add a new task..." autocomplete="off">
      <button type="submit">Add</button>
    </form>
    <ul id="todoList"></ul>
    <p id="summary"></p>
  </div>
  <script src="script.js"></script>
</body>
</html>

style.css

body {
  font-family: Arial, sans-serif;
  background: #e8f0fe;
  display: flex;
  justify-content: center;
  padding: 30px 16px;
  margin: 0;
}
.app {
  background: #fff;
  width: 100%;
  max-width: 420px;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 14px rgba(0, 0, 0, 0.12);
}
h1 { margin-top: 0; text-align: center; font-size: 24px; }
#todoForm { display: flex; gap: 8px; }
#todoInput {
  flex: 1;
  padding: 10px;
  border: 2px solid #ccc;
  border-radius: 6px;
  font-size: 15px;
}
#todoForm button {
  padding: 10px 16px;
  border: none;
  border-radius: 6px;
  background: #1a56a0;
  color: #fff;
  cursor: pointer;
}
ul { list-style: none; padding: 0; margin: 16px 0 0; }
li {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  border-bottom: 1px solid #eee;
}
li span { flex: 1; cursor: pointer; }
li.done span { text-decoration: line-through; color: #999; }
li button {
  border: none;
  background: #ffebee;
  color: #d32f2f;
  border-radius: 6px;
  padding: 4px 9px;
  cursor: pointer;
}
#summary { text-align: center; color: #666; font-size: 14px; }

script.js

const form = document.getElementById("todoForm");
const input = document.getElementById("todoInput");
const list = document.getElementById("todoList");
const summary = document.getElementById("summary");

// Load saved tasks (or start with an empty list)
let todos = JSON.parse(localStorage.getItem("todos")) || [];

function save() {
  localStorage.setItem("todos", JSON.stringify(todos));
}

function render() {
  list.innerHTML = "";
  todos.forEach(function (todo, index) {
    const li = document.createElement("li");
    if (todo.done) li.classList.add("done");

    const text = document.createElement("span");
    text.textContent = todo.text; // textContent is safe from HTML injection
    text.addEventListener("click", function () {
      todos[index].done = !todos[index].done;
      save();
      render();
    });

    const del = document.createElement("button");
    del.textContent = "✕";
    del.addEventListener("click", function () {
      todos.splice(index, 1);
      save();
      render();
    });

    li.appendChild(text);
    li.appendChild(del);
    list.appendChild(li);
  });

  const left = todos.filter(t => !t.done).length;
  summary.textContent = todos.length === 0
    ? "No tasks yet. Add one above!"
    : left + " of " + todos.length + " tasks left";
}

form.addEventListener("submit", function (e) {
  e.preventDefault();
  const value = input.value.trim();
  if (value === "") return;
  todos.push({ text: value, done: false });
  input.value = "";
  save();
  render();
});

render();

Challenge: Add an Edit button and a filter for All, Active and Completed tasks.

Mini Project 7: Quiz App (after Day 26)

A multiple-choice quiz with scoring and a result screen. Practices arrays of objects, loops, events and showing or hiding content.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JavaScript Quiz</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="quiz">
    <div id="quizBox">
      <p id="progress"></p>
      <h2 id="question"></h2>
      <div id="options"></div>
      <button id="next" disabled>Next</button>
    </div>
    <div id="result" class="hidden">
      <h2>Quiz finished!</h2>
      <p id="score"></p>
      <button id="restart">Try again</button>
    </div>
  </div>
  <script src="script.js"></script>
</body>
</html>

style.css

body {
  font-family: Arial, sans-serif;
  background: #ede7f6;
  display: flex;
  justify-content: center;
  padding: 30px 16px;
  margin: 0;
}
.quiz {
  background: #fff;
  width: 100%;
  max-width: 460px;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 14px rgba(0, 0, 0, 0.12);
}
#progress { color: #666; font-size: 14px; margin: 0; }
#options button {
  display: block;
  width: 100%;
  text-align: left;
  padding: 12px;
  margin: 8px 0;
  border: 2px solid #ccc;
  border-radius: 8px;
  background: #fff;
  font-size: 16px;
  cursor: pointer;
}
#options button:hover:not(:disabled) { border-color: #5e35b1; }
#options button.correct { background: #c8e6c9; border-color: #2e7d32; }
#options button.wrong { background: #ffcdd2; border-color: #d32f2f; }
#next, #restart {
  margin-top: 10px;
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  background: #5e35b1;
  color: #fff;
  font-size: 16px;
  cursor: pointer;
}
#next:disabled { background: #b39ddb; cursor: not-allowed; }
.hidden { display: none; }

script.js

const questions = [
  {
    question: "Which keyword declares a variable that cannot be reassigned?",
    options: ["let", "var", "const", "static"],
    answer: 2
  },
  {
    question: "What does typeof \"hello\" return?",
    options: ["text", "string", "word", "char"],
    answer: 1
  },
  {
    question: "Which method adds an item to the end of an array?",
    options: ["push()", "pop()", "shift()", "add()"],
    answer: 0
  },
  {
    question: "Which symbol is the strict equality operator?",
    options: ["=", "==", "===", "!="],
    answer: 2
  },
  {
    question: "Which method turns a JSON string into an object?",
    options: ["JSON.stringify()", "JSON.parse()", "JSON.object()", "JSON.read()"],
    answer: 1
  }
];

let index = 0;
let score = 0;
let answered = false;

const quizBox = document.getElementById("quizBox");
const resultBox = document.getElementById("result");
const progress = document.getElementById("progress");
const questionEl = document.getElementById("question");
const optionsEl = document.getElementById("options");
const nextBtn = document.getElementById("next");

function showQuestion() {
  const q = questions[index];
  answered = false;
  nextBtn.disabled = true;
  nextBtn.textContent = index === questions.length - 1 ? "Finish" : "Next";
  progress.textContent = "Question " + (index + 1) + " of " + questions.length;
  questionEl.textContent = q.question;
  optionsEl.innerHTML = "";

  q.options.forEach(function (text, i) {
    const btn = document.createElement("button");
    btn.textContent = text;
    btn.addEventListener("click", function () { choose(i); });
    optionsEl.appendChild(btn);
  });
}

function choose(i) {
  if (answered) return;
  answered = true;
  const correct = questions[index].answer;
  const buttons = optionsEl.querySelectorAll("button");

  if (i === correct) score++;
  buttons[correct].classList.add("correct");
  if (i !== correct) buttons[i].classList.add("wrong");
  buttons.forEach(b => b.disabled = true);
  nextBtn.disabled = false;
}

nextBtn.addEventListener("click", function () {
  index++;
  if (index < questions.length) {
    showQuestion();
  } else {
    quizBox.classList.add("hidden");
    resultBox.classList.remove("hidden");
    document.getElementById("score").textContent =
      "You scored " + score + " out of " + questions.length;
  }
});

document.getElementById("restart").addEventListener("click", function () {
  index = 0;
  score = 0;
  resultBox.classList.add("hidden");
  quizBox.classList.remove("hidden");
  showQuestion();
});

showQuestion();

Challenge: Add 5 more questions, shuffle their order, and save the highest score in localStorage.

Tips to Succeed

  • Code daily. Consistency beats long, irregular sessions.
  • Don't just watch tutorials. Type the code yourself and break it on purpose to learn.
  • Use MDN Web Docs as your main reference.
  • Debug patiently. Reading error messages is a core skill.
  • Revise on weekends before starting a new week.
What next? After 30 days, learn Git and GitHub, then move to a framework like React, and explore Node.js for backend development.

Did you follow this roadmap? Share your progress or questions in the comments below!

Reactions

Post a Comment

0 Comments