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
- Follow daily β Spend 30β60 minutes per day.
- Type the code β Donβt just copy-paste, practice typing and running it.
- Experiment β Change values, break code, and fix it β thatβs how you learn.
- Do the quizzes β They test your understanding.
- 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
- Print your name and your favorite hobby.
- 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
- Create a variable for your city.
- Create a constant for your birth year.
- 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
- Write an expression to check if age β₯ 18.
- 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
- Ask for a userβs name and output “Hello, NAME!”.
- 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
- Generate a random dice roll (1β6).
- 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
- Check if a number is even/odd.
- 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
- Write a program that checks if a number is positive, negative, or zero.
- 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
- Print numbers 1β10 using a for loop.
- Use a while loop to sum numbers 1β100.
- 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
- Write a function square(num) that returns the square.
- 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
- Write a function with a local variable and try accessing it outside.
- 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
- Convert a traditional function into an arrow function.
- 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
- Write a function that checks if a word is a palindrome.
- Write a loop that prints the multiplication table of 5.
- 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
- Add a function to remove a task by index.
- 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
- Create an array of 5 colors. Print the first and last.
- 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
- Double every number in [2, 4, 6].
- Filter out odd numbers from [5, 6, 7, 8].
- 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
- Create an object for a book (title, author, year).
- 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
- Add a method ageIn5Years() that returns future age.
- 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
- Create an object school with students array. Each student has name and grade.
- 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
- Destructure title and author from a book object.
- 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
- Add a function to search by name.
- 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
- Change the background color of the <body>.
- 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
- Show an alert when a paragraph is clicked.
- 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
- Make a button that toggles background color.
- 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
- Make a form with age input; print βAdultβ or βMinor.β
- 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
- Save a favorite color in localStorage. Retrieve it later.
- 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
- Fetch a random user from https://randomuser.me/api/.
- 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
- Write try/catch for dividing by zero.
- 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
- Track score and display at end.
- 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.”
