30 days to JavaScript Coding Introduction to Learning JavaScript

Introduction to Learning JavaScript

🌍 Why JavaScript Matters

JavaScript is the language of the web. It’s everywhere:

  • It powers interactive websites (animations, forms, navigation menus).
  • It runs inside browsers on laptops, phones, and tablets.
  • With frameworks like Node.js, it also powers the backend (servers).
  • It’s used in mobile apps, desktop apps, and even IoT devices.

In short: if you want to become a web developer, JavaScript is unavoidable.


🎯 Purpose of This Guide

This 30-day learning roadmap is designed to take you from complete beginner to intermediate-level JavaScript developer.

Each day includes:

  • πŸ“– Detailed explanations of key concepts
  • πŸ’» Multiple code examples broken down step by step
  • βœ… Exercises to practice
  • πŸ“ Quizzes with answers and explanations
  • πŸ’‘ AI learning prompts (to use with ChatGPT, Gemini, or similar tools)

By the end, you’ll be able to:

  • Understand JavaScript fundamentals
  • Write clean, working code
  • Build mini projects (like calculators, to-do apps, and quiz apps)
  • Tackle intermediate concepts like APIs, error handling, and DOM manipulation

🧠 Why This Approach Works

Most tutorials either give too little detail (leaving learners lost) or dump too much theory without showing real usage.

This guide focuses on:

  • Learn by Doing β†’ You’ll code daily, not just read.
  • Small Daily Wins β†’ Each lesson builds toward projects.
  • Reinforcement β†’ Exercises and quizzes make concepts stick.
  • AI Mentorship β†’ You’ll practice using AI tools to explain, debug, and expand on lessons.

πŸ”‘ Key Benefits of This Guide

  • Structured 30-day roadmap β†’ no confusion about what to learn next.
  • Multiple examples per concept β†’ see it in action.
  • Exercises + Quizzes β†’ reinforce learning.
  • Projects β†’ apply everything in real-world scenarios.
  • AI prompts β†’ practice guided learning and problem-solving.

πŸ“˜ How to Use This Guide

  1. Follow daily β†’ Spend 30–60 minutes per day.
  2. Type the code β†’ Don’t just copy-paste, practice typing and running it.
  3. Experiment β†’ Change values, break code, and fix it β€” that’s how you learn.
  4. Do the quizzes β†’ They test your understanding.
  5. Talk to AI tools β†’ Use the prompts to go deeper.

πŸ€– Example AI Prompts

Here are sample prompts to use with ChatGPT or Gemini:

  • β€œExplain the difference between let, const, and var with examples and analogies.”
  • β€œDebug this code: [paste code] β€” why is it failing?”
  • β€œCreate 3 practice problems about arrays with increasing difficulty.”
  • β€œGive me alternative ways to solve this function challenge.”

Practicing with AI will speed up your learning and help you become comfortable working with tools that many modern developers rely on.


πŸš€ Tips for Success

  • Practice every day β†’ consistency > cramming.
  • Don’t fear errors β†’ each bug is a learning opportunity.
  • Read explanations carefully β†’ then apply them in code.
  • Save your projects β†’ you’ll see how much progress you’ve made.
  • Use AI as a tutor, not a crutch β†’ try first, then ask for help.

πŸ“ˆ The Road Ahead

After this 30-day journey, you’ll:

  • Know how to write, debug, and structure JavaScript code.
  • Be able to build small but complete projects.
  • Be ready to explore modern frameworks like React, Vue, or Angular.
  • Have the confidence to continue into full-stack development with Node.js.

This is your launchpad into coding.
Now let’s begin your JavaScript journey!

πŸ—“οΈ Week 1: JavaScript Foundations 

πŸ“˜ Week 1: JavaScript Foundations

Focus: Learning the very basics of JavaScript β€” how it works, how to write code, and how to think like a programmer.

In this first week, you’ll:

  • Understand what JavaScript is and where it runs.
  • Learn about variables, data types, and operators.
  • Work with strings, numbers, and booleans.
  • Start using logic with if/else statements.
  • Build your very first mini project (a grade calculator).

πŸ’‘ Why it matters:
Just like learning a new language starts with the alphabet and simple words, coding starts with variables, types, and operators. This week gives you the building blocks you’ll use every single day as a developer.

Day 1: Introduction to JavaScript

🎯 Goal

Understand what JavaScript is, how it runs in browsers, and write your very first script.

πŸ“– Explanation

JavaScript is the programming language of the web. It makes static pages interactive:

  • HTML β†’ Content (text, images, structure)
  • CSS β†’ Style (colors, fonts, layout)
  • JavaScript β†’ Behavior (animations, user interaction, logic)

When you click a button and see something change on a webpage β†’ that’s JavaScript.

πŸ’» First Code

console.log(“Hello, JavaScript!”);

πŸ” Explanation

  • console.log β†’ a function that outputs text or values to the browser’s console (a developer tool).
  • “Hello, JavaScript!” β†’ a string literal, enclosed in quotes.
  • ; β†’ optional, but often used to mark the end of a statement.

➑️ Open your browser β†’ Right-click β†’ Inspect β†’ Console β†’ Paste code β†’ Press Enter.

βœ… Exercise

  1. Print your name and your favorite hobby.
  2. Print today’s date using console.log(“Today is …”).

πŸ“ Quiz Question

Q: What does console.log(5 + 3); print?

  • a) “5 + 3”
  • b) 53
  • c) 8
  • d) Error

Answer: c) 8

  • Because + is an arithmetic operator when used with numbers.

πŸ’‘ AI Prompt

“Explain console.log like I’m 10 years old, then give me 3 fun exercises to practice it.”

Day 2: Variables and Data Types

🎯 Goal

Learn how to store values and understand JavaScript’s types of data.

πŸ“– Explanation

Variables are containers that hold information. Think of them as labeled boxes.

  • let β†’ reassignable values.
  • const β†’ fixed (constant) values.
  • var β†’ older way, avoid for now.

πŸ’» Code

let name = “Lars”;   // a string

const age = 30;      // a number

let isLearning = true; // a boolean

console.log(name, age, isLearning);

πŸ” Explanation

  • “Lars” β†’ a string (text inside quotes).
  • 30 β†’ a number (no quotes).
  • true β†’ a boolean (only true or false).
  • console.log(name, age) β†’ prints multiple values separated by a space.

πŸ“Š Data Types

  • String β†’ “Hello”
  • Number β†’ 42, 3.14
  • Boolean β†’ true, false
  • Null β†’ empty on purpose
  • Undefined β†’ declared but not given a value
  • Object β†’ { key: “value” }

βœ… Exercise

  1. Create a variable for your city.
  2. Create a constant for your birth year.
  3. Log “My name is [name] and I live in [city].”

πŸ“ Quiz

Q: What’s the output?

let x;

console.log(x);

Answer: undefined β†’ because we declared x but didn’t assign a value.

πŸ’‘ AI Prompt

“Show me real-world examples of variables as boxes or containers. Give me analogies.”

Day 3: Operators

🎯 Goal

Perform calculations and comparisons.

πŸ“– Explanation

Operators act on values:

  • Arithmetic: + – * / % **
  • Comparison: == === != !== < > <= >=
  • Logical: && || !

πŸ’» Code

let a = 10, b = 3;

console.log(a + b);  // 13

console.log(a % b);  // 1 (remainder)

console.log(a ** b); // 1000 (power)

console.log(a > b);  // true

console.log(a === “10”); // false

πŸ” Explanation

  • % gives remainder.
  • === checks both value and type.
  • “10” is a string, not a number β†’ === returns false.

βœ… Exercise

  1. Write an expression to check if age β‰₯ 18.
  2. Check if “apple” === “Apple”.

πŸ“ Quiz

Q: What’s the result?

console.log(5 == “5”);

console.log(5 === “5”);

Answer:

  • First β†’ true (loose comparison, converts string).
  • Second β†’ false (strict, different types).

Day 4: Strings

🎯 Goal

Work with text, formatting, and built-in methods.

πŸ“– Explanation

Strings are sequences of characters. You can join them (concatenation) or use template literals.

πŸ’» Code

let first = “Java”;

let second = “Script”;

console.log(first + second); // JavaScript

console.log(`${first} ${second}`); // Java Script

let msg = “I love JavaScript!”;

console.log(msg.length); // 18

console.log(msg.toUpperCase()); // I LOVE JAVASCRIPT!

console.log(msg.includes(“love”)); // true

πŸ” Explanation

  • .length counts characters.
  • .toUpperCase() changes to caps.
  • .includes(“love”) checks for substring.

βœ… Exercise

  1. Ask for a user’s name and output “Hello, NAME!”.
  2. Count the characters in “JavaScript is fun”.

πŸ“ Quiz

Q: What’s the output?

console.log(“Hello”.toLowerCase());

Answer: “hello”

Day 5: Numbers and Math

🎯 Goal

Understand numeric operations and the Math object.

πŸ“– Explanation

Numbers can be integers or decimals. JavaScript has a built-in Math object for math operations.

πŸ’» Code

let num = 4.7;

console.log(Math.round(num)); // 5

console.log(Math.floor(num)); // 4

console.log(Math.ceil(num));  // 5

console.log(Math.random());   // random 0-1

console.log(Math.floor(Math.random() * 10) + 1); // random 1-10

πŸ” Explanation

  • round β†’ nearest integer.
  • floor β†’ down.
  • ceil β†’ up.
  • random() β†’ generates a number between 0 and 1.

βœ… Exercise

  1. Generate a random dice roll (1–6).
  2. Calculate the square root of 64.

πŸ“ Quiz

Q: What’s the result?

console.log(Math.max(2, 8, 5));

Answer: 8

Day 6: Booleans and Logic

🎯 Goal

Learn decision-making in code with true/false.

πŸ“– Explanation

Booleans help us write conditions:

let isStudent = true;

if (isStudent) {

  console.log(“You get a discount!”);

} else {

  console.log(“No discount.”);

}

πŸ” Explanation

  • if (condition) runs code if true.
  • else runs if false.

βœ… Exercise

  1. Check if a number is even/odd.
  2. Write a condition: if temperature > 30 β†’ “Hot day”.

πŸ“ Quiz

Q: What prints?

let hungry = false;

if (!hungry) console.log(“Not hungry”);

Answer: “Not hungry”

Day 7: Review Project

🎯 Goal

Combine variables, operators, conditionals into a mini project.

πŸ’» Code – Grade Calculator

let score = 85;

if (score >= 90) {

  console.log(“Grade: A”);

} else if (score >= 75) {

  console.log(“Grade: B”);

} else if (score >= 60) {

  console.log(“Grade: C”);

} else {

  console.log(“Grade: F”);

}

βœ… Exercise

Modify program to:

  • Ask for user’s score (prompt in browser).
  • Print grade + message.

πŸ’‘ AI Learning Prompt for Week 1
“Act as my JavaScript tutor. Review my grade calculator code and suggest at least 2 improvements. Then give me 3 more practice challenges that build on it.”

πŸ—“οΈ Week 2: Control Flow and Functions

πŸ“˜ Week 2: Control Flow and Functions

Focus: Making your code smart with decisions, loops, and reusable blocks of code.

This week, you’ll:

  • Write code that decides (if/else, switch).
  • Automate repetition with loops.
  • Create and use functions to organize your code.
  • Understand scope and hoisting.
  • Learn arrow functions for modern, clean syntax.
  • Build a console-based to-do app.

πŸ’‘ Why it matters:
Programming isn’t just about storing data β€” it’s about making decisions and reusing logic. By the end of this week, you’ll be able to write programs that adapt to input and handle more complex tasks without repetition.

Day 8: If/Else and Switch Statements

🎯 Goal

Learn how to control the program’s flow by making decisions.

πŸ“– Explanation

  • if/else lets us execute code depending on conditions.
  • switch is useful for multiple possible values.

πŸ’» Code – If/Else

let age = 20;

if (age >= 18) {

  console.log(“You are an adult.”);

} else {

  console.log(“You are a minor.”);

}

πŸ” Explanation

  • If condition is true β†’ first block runs.
  • Otherwise β†’ second block runs.

πŸ’» Code – Switch

let color = “blue”;

switch (color) {

  case “red”:

    console.log(“Stop!”);

    break;

  case “green”:

    console.log(“Go!”);

    break;

  case “blue”:

    console.log(“Cool and calm.”);

    break;

  default:

    console.log(“Unknown color”);

}

πŸ” Explanation

  • Each case is checked against color.
  • break stops further checking.
  • default runs if no match.

βœ… Exercises

  1. Write a program that checks if a number is positive, negative, or zero.
  2. Use a switch to print the day of the week (1–7).

πŸ“ Quiz

Q: What’s the output?

let x = 10;

if (x > 15) {

  console.log(“Big”);

} else {

  console.log(“Small”);

}

Answer: β€œSmall” – because 10 is not greater than 15.

πŸ’‘ AI Prompt

“Give me 5 different scenarios where if/else is better than switch, and vice versa.”

Day 9: Loops (For, While, Do…While)

🎯 Goal

Repeat actions without rewriting code.

πŸ“– Explanation

Loops let us automate repetition.

πŸ’» Code – For Loop

for (let i = 1; i <= 5; i++) {

  console.log(“Count:”, i);

}

πŸ” Explanation

  • let i = 1 β†’ start.
  • i <= 5 β†’ condition.
  • i++ β†’ update after each loop.

πŸ’» Code – While Loop

let num = 1;

while (num <= 5) {

  console.log(num);

  num++;

}

πŸ’» Code – Do…While

let x = 1;

do {

  console.log(“Value:”, x);

  x++;

} while (x <= 3);

πŸ” Difference

  • while checks before running.
  • do…while always runs at least once.

βœ… Exercises

  1. Print numbers 1–10 using a for loop.
  2. Use a while loop to sum numbers 1–100.
  3. Use a do…while loop to print “Try again” until a counter reaches 3.

πŸ“ Quiz

Q: What’s the output?

for (let i = 0; i < 3; i++) {

  console.log(“Hi”);

}

Answer: “Hi” printed 3 times.

πŸ’‘ AI Prompt

“Explain the difference between while and do…while with real-life analogies.”

Day 10: Functions

🎯 Goal

Encapsulate reusable blocks of code.

πŸ“– Explanation

Functions are like recipes: give them ingredients (parameters), and they return a dish (output).

πŸ’» Code – Basic Function

function greet(name) {

  return `Hello, ${name}!`;

}

console.log(greet(“Lars”)); 

πŸ” Explanation

  • function greet(name) β†’ defines a function.
  • name β†’ parameter.
  • return β†’ sends back a result.

βœ… Exercises

  1. Write a function square(num) that returns the square.
  2. Write a function that adds 2 numbers.

πŸ“ Quiz

Q: What happens if a function has no return?
Answer: It returns undefined by default.

πŸ’‘ AI Prompt

“Give me 3 exercises to practice functions, then check my answers.”

Day 11: Scope and Hoisting

🎯 Goal

Understand where variables live and how they behave.

πŸ“– Explanation

  • Global scope β†’ accessible everywhere.
  • Local scope β†’ inside a function.
  • var is function-scoped, let and const are block-scoped.
  • Hoisting β†’ JavaScript moves declarations to the top during execution.

πŸ’» Code

let x = 10; // global

function test() {

  let y = 5; // local

  console.log(x + y);

}

test(); 

console.log(x);

// console.log(y); // Error

βœ… Exercises

  1. Write a function with a local variable and try accessing it outside.
  2. Test difference between var and let in loops.

πŸ“ Quiz

Q: What’s hoisting?
Answer: Declarations are moved to the top before execution, but initializations are not.

Day 12: Arrow Functions

🎯 Goal

Use modern, shorter syntax for functions.

πŸ“– Explanation

Arrow functions are concise and do not have their own this.

πŸ’» Code

const add = (a, b) => a + b;

console.log(add(5, 3)); // 8

πŸ” Explanation

  • => replaces function.
  • Works well for small, simple functions.

βœ… Exercises

  1. Convert a traditional function into an arrow function.
  2. Write an arrow function to check if a number is even.

πŸ“ Quiz

Q: What’s the output?

const greet = name => “Hi ” + name;

console.log(greet(“Sam”));

Answer: “Hi Sam”

Day 13: Practice Exercises

βœ… Tasks

  1. Write a function that checks if a word is a palindrome.
  2. Write a loop that prints the multiplication table of 5.
  3. Use a switch to build a simple calculator (add, subtract, multiply, divide).

πŸ“ Quiz

Q: Which is better for reusability: writing the same code multiple times, or putting it in a function?
Answer: Function β†’ because it avoids duplication and increases clarity.

Day 14: Mini Project – Console To-Do App

🎯 Goal

Apply everything learned in Weeks 1–2.

πŸ’» Code

let tasks = [];

function addTask(task) {

  tasks.push(task);

  console.log(`Added: ${task}`);

}

function showTasks() {

  console.log(“Tasks:”);

  tasks.forEach((task, index) => {

    console.log(`${index + 1}. ${task}`);

  });

}

addTask(“Learn JS”);

addTask(“Practice functions”);

showTasks();

πŸ” Explanation

  • tasks β†’ array storing tasks.
  • push() β†’ adds new task.
  • forEach() β†’ loops through tasks.

βœ… Challenge

  1. Add a function to remove a task by index.
  2. Prevent empty tasks from being added.

πŸ—“οΈ Week 3: Arrays and Objects

πŸ“˜ Week 3: Arrays and Objects

Focus: Handling collections of data and modeling real-world things in code.

This week, you’ll:

  • Master arrays β€” lists of items you can loop over.
  • Learn array methods like map, filter, and forEach.
  • Work with objects, which store data in key-value pairs.
  • Explore nested arrays and objects for complex data.
  • Use destructuring and the spread operator.
  • Build a contact list project combining arrays and objects.

πŸ’‘ Why it matters:
Real applications rely on managing lots of data β€” users, tasks, products, scores. Arrays and objects are the heart of JavaScript programming. Once you get comfortable here, you can model almost anything in code

Day 15: Arrays (Basics)

🎯 Goal

Learn how to store and access lists of data.

πŸ“– Explanation

An array is like a row of boxes where each box holds a value. Each value has an index (starting from 0).

πŸ’» Code

let fruits = [“apple”, “banana”, “cherry”];

console.log(fruits[0]); // apple

console.log(fruits[2]); // cherry

fruits[1] = “blueberry”; // change value

console.log(fruits);

πŸ” Explanation

  • [ ] β†’ defines an array.
  • fruits[0] β†’ gets the first item.
  • Arrays can be modified after creation.

Common Methods

  • push() β†’ add to end
  • pop() β†’ remove last item
  • shift() β†’ remove first item
  • unshift() β†’ add to start

fruits.push(“mango”);

console.log(fruits); 

βœ… Exercises

  1. Create an array of 5 colors. Print the first and last.
  2. Add and remove items using push, pop, shift, unshift.

πŸ“ Quiz

Q: What’s the output?

let nums = [1, 2, 3];

nums.push(4);

console.log(nums.length);

Answer: 4 – after push, array has 4 items.

πŸ’‘ AI Prompt

“Explain arrays with a real-world analogy, like a bookshelf. Then give me 3 practice problems.”

Day 16: Array Iteration (forEach, map, filter)

🎯 Goal

Learn how to loop through arrays and transform them.

πŸ’» Code – forEach

let numbers = [1, 2, 3, 4];

numbers.forEach(num => console.log(num * 2));

πŸ” Explanation

  • forEach β†’ executes a function for each element.

πŸ’» Code – map

let squares = numbers.map(num => num * num);

console.log(squares); // [1, 4, 9, 16]

πŸ” Explanation

  • map β†’ creates a new array by transforming elements.

πŸ’» Code – filter

let evens = numbers.filter(num => num % 2 === 0);

console.log(evens); // [2, 4]

πŸ” Explanation

  • filter β†’ creates a new array with elements that pass a condition.

βœ… Exercises

  1. Double every number in [2, 4, 6].
  2. Filter out odd numbers from [5, 6, 7, 8].
  3. Map strings in [“js”, “html”] to uppercase.

πŸ“ Quiz

Q: What’s the difference between map and forEach?
Answer: map returns a new array; forEach does not.

πŸ’‘ AI Prompt

“Give me 5 challenges mixing map and filter. Provide hints, not answers.”

Day 17: Objects (Basics)

🎯 Goal

Learn to store data as key-value pairs.

πŸ“– Explanation

Objects group related data. Think of them as labeled filing cabinets.

πŸ’» Code

let person = {

  name: “Lars”,

  age: 35,

  isStudent: false

};

console.log(person.name);  // dot notation

console.log(person[“age”]); // bracket notation

πŸ” Explanation

  • name: “Lars” β†’ key-value pair.
  • Access with dot or bracket notation.

βœ… Exercises

  1. Create an object for a book (title, author, year).
  2. Access and print its properties.

πŸ“ Quiz

Q: What’s the output?

let car = { brand: “Toyota”, year: 2020 };

console.log(car.color);

Answer: undefined – property doesn’t exist.

πŸ’‘ AI Prompt

“Explain objects with analogy of a contact card. Then give me 3 practice problems.”

Day 18: Object Methods and this

🎯 Goal

Add functions inside objects and understand this.

πŸ’» Code

let user = {

  name: “Alice”,

  greet: function() {

    console.log(“Hello, my name is ” + this.name);

  }

};

user.greet(); 

πŸ” Explanation

  • A method is a function inside an object.
  • this refers to the object itself (user).

βœ… Exercises

  1. Add a method ageIn5Years() that returns future age.
  2. Create a method isAdult() that returns true/false.

πŸ“ Quiz

Q: What’s the output?

let obj = { val: 42, show: () => console.log(this.val) };

obj.show();

Answer: undefined – arrow functions don’t bind this.

πŸ’‘ AI Prompt

“Show me 3 ways this behaves differently in regular vs arrow functions.”

Day 19: Nested Objects & Arrays

🎯 Goal

Handle more complex data structures.

πŸ’» Code

let company = {

  name: “TechCo”,

  employees: [

    { name: “Bob”, role: “Developer” },

    { name: “Sue”, role: “Designer” }

  ]

};

console.log(company.employees[0].name); // Bob

πŸ” Explanation

  • Arrays can hold objects.
  • Objects can hold arrays.
  • Access using chaining.

βœ… Exercises

  1. Create an object school with students array. Each student has name and grade.
  2. Print the first student’s grade.

πŸ“ Quiz

Q: What’s the output?

let data = { items: [ {id: 1}, {id: 2} ] };

console.log(data.items[1].id);

Answer: 2

Day 20: Destructuring & Spread Operator

🎯 Goal

Write cleaner code by unpacking and merging values.

πŸ’» Code – Destructuring

let person = { name: “Lars”, age: 35 };

let { name, age } = person;

console.log(name, age);

πŸ’» Code – Spread

let arr1 = [1, 2];

let arr2 = [3, 4];

let combined = […arr1, …arr2];

console.log(combined); // [1,2,3,4]

πŸ” Explanation

  • { name, age } extracts properties.
  • … spreads array elements or object properties.

βœ… Exercises

  1. Destructure title and author from a book object.
  2. Merge two arrays [a,b] and [c,d].

πŸ“ Quiz

Q: What’s the output?

let a = [1,2];

let b = […a,3];

console.log(b);

Answer: [1,2,3]

Day 21: Project – Contact List with Objects

🎯 Goal

Apply arrays, objects, and methods.

πŸ’» Code

let contacts = [];

function addContact(name, phone) {

  contacts.push({ name, phone });

  console.log(`Added: ${name}`);

}

function showContacts() {

  contacts.forEach(c => console.log(`${c.name}: ${c.phone}`));

}

addContact(“Alice”, “123-456”);

addContact(“Bob”, “987-654”);

showContacts();

πŸ” Explanation

  • contacts β†’ array of objects.
  • Each object has name and phone.
  • forEach β†’ loops through contacts.

βœ… Challenge

  1. Add a function to search by name.
  2. Add a function to delete a contact.

πŸ’‘ AI Prompt for Week 3
“Review my contact list project. Suggest improvements like searching, editing, or sorting. Then give me 3 practice tasks with nested arrays and objects.”

πŸ—“οΈ Week 4: DOM, Events, Async & Final Projects

πŸ“˜ Week 4: DOM, Events, Async & Final Projects

Focus: Connecting JavaScript to the browser, making pages interactive, saving data, and fetching external information.

This week, you’ll:

  • Learn how JavaScript interacts with HTML using the DOM.
  • Add event listeners for clicks, key presses, and form submissions.
  • Change page content and styles dynamically.
  • Store and retrieve data with localStorage.
  • Fetch data from external APIs using fetch.
  • Handle errors gracefully with try/catch.
  • Build a full interactive quiz app.
  • Wrap up with next steps for advancing your skills.

πŸ’‘ Why it matters:
This is where JavaScript becomes visible and exciting. You’ll see your code bring web pages to life β€” responding to users, saving data, and even talking to the internet. By the end of this week, you’ll have all the skills needed to build real, interactive projects.

Day 22: DOM Basics

🎯 Goal

Learn how to access and modify HTML elements with JavaScript.

πŸ“– Explanation

The DOM (Document Object Model) represents a webpage as a tree of objects. JavaScript can read and change it.

πŸ’» HTML + JS

<p id=”demo”>Hello World</p>

<script>

  let element = document.getElementById(“demo”);

  console.log(element.innerText); // Hello World

  element.innerText = “Changed with JS!”;

</script>

πŸ” Explanation

  • document β†’ represents the page.
  • getElementById(“demo”) β†’ finds an element by its ID.
  • .innerText β†’ reads or changes text content.

βœ… Exercises

  1. Change the background color of the <body>.
  2. Select a <h1> and replace its text.

πŸ“ Quiz

Q: What does document.querySelector(“.className”) select?
Answer: The first element with that class.

Day 23: Events and Event Listeners

🎯 Goal

Make web pages interactive with events.

πŸ“– Explanation

Events are actions like clicks, key presses, or form submissions.

πŸ’» HTML + JS

<button id=”btn”>Click Me</button>

<script>

  let btn = document.getElementById(“btn”);

  btn.addEventListener(“click”, () => {

    alert(“Button clicked!”);

  });

</script>

πŸ” Explanation

  • addEventListener(“click”, …) β†’ runs code when the button is clicked.

βœ… Exercises

  1. Show an alert when a paragraph is clicked.
  2. Log key presses using keydown.

πŸ“ Quiz

Q: Which is better practice: inline onclick or addEventListener?
Answer: addEventListener β†’ separates JS from HTML and allows multiple listeners.

Day 24: DOM Manipulation (Changing Styles and Elements)

🎯 Goal

Learn to dynamically change webpage content and style.

πŸ’» Code

<p id=”text”>Hello</p>

<button id=”change”>Change</button>

<script>

  let text = document.getElementById(“text”);

  let btn = document.getElementById(“change”);

  btn.addEventListener(“click”, () => {

    text.style.color = “red”;

    text.innerHTML = “<b>Text Updated!</b>”;

  });

</script>

πŸ” Explanation

  • .style.property β†’ changes CSS.
  • .innerHTML β†’ allows HTML tags inside.

βœ… Exercises

  1. Make a button that toggles background color.
  2. Create a button that adds a new <li> to a list.

Day 25: Forms and User Input

🎯 Goal

Collect and use user input.

πŸ’» Code

<input type=”text” id=”nameInput” placeholder=”Enter name”>

<button id=”greetBtn”>Greet</button>

<p id=”output”></p>

<script>

  document.getElementById(“greetBtn”).addEventListener(“click”, () => {

    let name = document.getElementById(“nameInput”).value;

    document.getElementById(“output”).innerText = `Hello, ${name}!`;

  });

</script>

πŸ” Explanation

  • .value β†’ gets input field’s content.
  • Output updated when button is clicked.

βœ… Exercises

  1. Make a form with age input; print β€œAdult” or β€œMinor.”
  2. Build a login form that prints entered username.

Day 26: JSON and LocalStorage

🎯 Goal

Save and retrieve data inside the browser.

πŸ“– Explanation

  • JSON = JavaScript Object Notation β†’ text-based data format.
  • LocalStorage β†’ stores key-value pairs in browser permanently.

πŸ’» Code

let user = { name: “Lars”, age: 35 };

localStorage.setItem(“user”, JSON.stringify(user));

let storedUser = JSON.parse(localStorage.getItem(“user”));

console.log(storedUser.name); // Lars

πŸ” Explanation

  • JSON.stringify β†’ object β†’ string.
  • JSON.parse β†’ string β†’ object.

βœ… Exercises

  1. Save a favorite color in localStorage. Retrieve it later.
  2. Save an array of tasks and display them.

Day 27: Fetch API (Getting Data from the Web)

🎯 Goal

Make HTTP requests to external APIs.

πŸ’» Code

fetch(“https://jsonplaceholder.typicode.com/posts/1”)

  .then(response => response.json())

  .then(data => console.log(data))

  .catch(error => console.error(“Error:”, error));

πŸ” Explanation

  • fetch(url) β†’ sends request.
  • .then(response => response.json()) β†’ parses JSON response.
  • .catch β†’ handles errors.

βœ… Exercises

  1. Fetch a random user from https://randomuser.me/api/.
  2. Fetch posts and display titles in the console.

πŸ“ Quiz

Q: Why do we use .json() after fetch?
Answer: Converts raw response into usable JSON object.

Day 28: Error Handling (try/catch)

🎯 Goal

Prevent crashes by handling errors.

πŸ’» Code

try {

  let result = riskyFunction();

  console.log(result);

} catch (error) {

  console.error(“Something went wrong:”, error.message);

}

πŸ” Explanation

  • try β†’ code that may fail.
  • catch β†’ runs if error occurs.

βœ… Exercises

  1. Write try/catch for dividing by zero.
  2. Wrap fetch request in try/catch.

Day 29: Project – Interactive Quiz App

🎯 Goal

Combine DOM, events, JSON, and logic.

πŸ’» HTML + JS (Simplified)

<div id=”quiz”></div>

<button id=”next”>Next</button>

<p id=”result”></p>

<script>

let questions = [

  { q: “2+2?”, a: “4” },

  { q: “Capital of France?”, a: “Paris” }

];

let index = 0;

function showQuestion() {

  let q = questions[index];

  document.getElementById(“quiz”).innerHTML =

    `<p>${q.q}</p><input id=”answer”>`;

}

document.getElementById(“next”).addEventListener(“click”, () => {

  let ans = document.getElementById(“answer”).value;

  if (ans === questions[index].a) {

    document.getElementById(“result”).innerText = “Correct!”;

  } else {

    document.getElementById(“result”).innerText = “Wrong!”;

  }

  index++;

  if (index < questions.length) showQuestion();

});

showQuestion();

</script>

πŸ” Explanation

  • Questions stored in an array of objects.
  • Dynamically display each question.
  • Check answers and give feedback.

βœ… Challenge

  1. Track score and display at end.
  2. Add multiple-choice questions.

Day 30: Wrap-Up and Next Steps

🎯 Goal

Review everything and set the path forward.

βœ… Concepts Mastered

  • Basics: variables, data types, operators
  • Control flow: if/else, loops, functions
  • Data handling: arrays, objects, JSON
  • DOM: selecting, events, manipulation
  • Advanced: localStorage, fetch, error handling
  • Projects: grade calculator, to-do app, contact list, quiz app

πŸ“– Next Steps

  • Learn ES6+ features (modules, async/await).
  • Explore frameworks: React, Vue, or Angular.
  • Try Node.js for backend.
  • Build projects: weather app, expense tracker, chat bot.

πŸ’‘ AI Learning Prompt

“I finished a 30-day JavaScript guide. Suggest 5 beginner-friendly projects to apply my knowledge, and explain which concepts each project will reinforce.”