Day 1: JavaScript Basics + Setting Up
Today, we’ll cover what JavaScript is, why it’s awesome, and how to set up your environment to start coding. Let’s dive in!
What is JavaScript?
JavaScript is the language that makes websites interactive. It’s what makes buttons work, forms validate, and pages update without refreshing. It runs in your browser, so you don’t need to install anything extra to start learning. JavaScript is also used on the server side (with Node.js) and in mobile apps (like React Native), but we’ll focus on the basics for now.
Setting Up Your Environment
To write JavaScript, you need two things:
- A browser (like Chrome, Firefox, or Edge).
- A text editor (like VS Code, Sublime Text, or even Notepad).
Here’s how to get started:
- Open your browser and press
F12
to open the Developer Tools. - Go to the “Console” tab. This is where you can type and test JavaScript code.
- Install a text editor like VS Code (it’s free and super helpful for writing code).
Your First JavaScript Code
Let’s write your first line of JavaScript! Open the browser console and type:
console.log("Hello, World!");
Press Enter, and you’ll see Hello, World!
printed in the console. Boom! You just wrote your first JavaScript code.
What’s Happening?
console.log()
is a function that prints whatever you put inside the parentheses."Hello, World!"
is a string (a piece of text).
Try This: Change the text inside console.log()
and see what happens.
Variables
Variables are like containers that store data. You can create them using let
, const
, or var
. Here’s how they work:
let name = "Naman";
const age = 25;
var isStudent = true;
let
is used for variables that can change.const
is used for variables that won’t change (constants).var
is the old way of declaring variables (avoid it for now).
Example:
let score = 10;
score = 20; // This works because `let` allows changes.
console.log(score); // Output: 20
const pi = 3.14;
pi = 3.15; // This will give an error because `const` can’t be changed.
Try This: Create a variable called city
and store your city’s name in it. Then print it using console.log()
.
Day 2: Data Types and Basic Operations
Today, we’ll learn about the different types of data JavaScript can handle and how to perform basic operations.
Data Types
JavaScript has different types of data. Here are the main ones:
- String: Text (e.g.,
"Hello"
). - Number: Numbers (e.g.,
10
,3.14
). - Boolean:
true
orfalse
. - Array: A list of items (e.g.,
[1, 2, 3]
). - Object: A collection of key-value pairs (e.g.,
{ name: "Amit", age: 25 }
).
Examples:
let name = "Lokesh"; // String
let age = 30; // Number
let isStudent = false; // Boolean
let fruits = ["Apple", "Banana", "Mango"]; // Array
let person = { name: "Lokesh", age: 24 }; // Object
Try This: Create a variable called hobbies
and store an array of your hobbies. Then print it.
Basic Math Operations
JavaScript can do math just like a calculator. Here are the basic operations:
- Addition (
+
) - Subtraction (
-
) - Multiplication (
*
) - Division (
/
) - Modulus (
%
) – gives the remainder of a division.
Examples:
let sum = 10 + 5; // 15
let difference = 10 - 5; // 5
let product = 10 * 5; // 50
let quotient = 10 / 5; // 2
let remainder = 10 % 3; // 1
Try This: Calculate the area of a rectangle (length * width) and print the result.
Day 3: Strings and Concatenation
Today, we’ll focus on working with text (strings) and combining them.
Strings
Strings are pieces of text. You can create them using single quotes ('
), double quotes ("
), or backticks (`
).
Examples:
let greeting = "Hello";
let name = 'Deepak';
let message = `Good morning`;
Concatenation
You can combine strings using the +
operator. This is called concatenation.
Examples:
let firstName = "Deepak";
let lastName = "Negi";
let fullName = firstName + " " + lastName;
console.log(fullName); // Output: Deepak Negi
Template Literals (Bonus):
You can also use backticks (`
) to make it easier:
let fullName = `${firstName} ${lastName}`;
console.log(fullName); // Output: Deepak Negi
Try This: Create a variable called greeting
that says “Hello, [Your Name]!” and print it.
Day 4: If Statements
Today, we’ll learn how to make decisions in your code using if
statements.
If Statements
If statements let you run code only if a condition is true
.
Example:
let age = 18;
if (age >= 18) {
console.log("You're an adult!");
} else {
console.log("You're a kid!");
}
Else If:
You can check multiple conditions using else if
.
Example:
let score = 85;
if (score >= 90) {
console.log("A grade!");
} else if (score >= 80) {
console.log("B grade!");
} else {
console.log("C grade!");
}
Try This: Write an if statement that checks if a number is positive, negative, or zero.
Day 5: Comparison and Logical Operators
Today, we’ll learn how to compare values and combine conditions.
Comparison Operators
Comparison operators let you compare values. Here are the main ones:
==
(equal to)===
(strict equal to – checks value AND type)!=
(not equal to)!==
(strict not equal to)>
(greater than)<
(less than)>=
(greater than or equal to)<=
(less than or equal to)
Examples:
let num = 10;
console.log(num > 5); // true
console.log(num === "10"); // false (because types are different)
Logical Operators
Logical operators let you combine conditions:
&&
(AND): Both conditions must be true.||
(OR): At least one condition must be true.!
(NOT): Reverses the condition.
Example:
let age = 20;
let hasLicense = true;
if (age >= 18 && hasLicense) {
console.log("You can drive!");
}
Try This: Write a condition that checks if a number is between 10 and 20.
Day 6: Arrays
Arrays are like lists that can store multiple values. They’re super useful for grouping related data.
Creating Arrays
You can create an array using square brackets []
.
Example:
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits); // Output: ["Apple", "Banana", "Mango"]
Accessing Array Items
You can access items in an array using their index (position). Indexes start at 0.
Example:
console.log(fruits[0]); // Output: "Apple"
console.log(fruits[2]); // Output: "Mango"
Updating Array Items
You can change the value of an item by assigning a new value to its index.
Example:
fruits[1] = "Grapes";
console.log(fruits); // Output: ["Apple", "Grapes", "Mango"]
Try This: Create an array called colors
with 3 colors and print the second color.
Day 7: Loops (For Loop)
Loops let you repeat a block of code multiple times. The for
loop is one of the most common loops.
For Loop Syntax
for (let i = 0; i < 5; i++) {
console.log(i);
}
let i = 0
: Start the loop withi
equal to 0.i < 5
: Keep looping as long asi
is less than 5.i++
: Increasei
by 1 after each loop.
Output:
0
1
2
3
4
Looping Through an Array
You can use a for
loop to go through each item in an array.
Example:
let fruits = ["Apple", "Banana", "Mango"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Output:
Apple
Banana
Mango
Try This: Create an array of numbers and use a for
loop to print each number.
Day 8: Functions
Functions are reusable blocks of code that perform a specific task. They help you avoid repeating code.
Creating a Function
Use the function
keyword to create a function.
Example:
function greet() {
console.log("Hello, World!");
}
greet(); // Output: Hello, World!
Functions with Parameters
You can pass data to a function using parameters.
Example:
function greet(name) {
console.log("Hello, " + name);
}
greet("Vishal"); // Output: Hello, Vishal
greet("Nitish"); // Output: Hello, Nitish
Returning Values
A function can return a value using the return
keyword.
Example:
function add(a, b) {
return a + b;
}
let result = add(5, 10);
console.log(result); // Output: 15
Try This: Write a function called multiply
that takes two numbers and returns their product.
Day 9: Objects
Objects are collections of key-value pairs. They’re used to store related data and functions.
Creating an Object
Use curly braces {}
to create an object.
Example:
let person = {
name: "Neha",
age: 25,
isStudent: true
};
console.log(person.name); // Output: Neha
console.log(person.age); // Output: 25
Updating an Object
You can add or change properties in an object.
Example:
person.age = 30;
person.city = "Dehradun";
console.log(person); // Output: { name: "Neha", age: 30, isStudent: true, city: "Dehradun" }
Methods in Objects
You can add functions (called methods) to an object.
Example:
let person = {
name: "Mohit",
greet: function() {
console.log("Hello, " + this.name);
}
};
person.greet(); // Output: Hello, Mohit
Try This: Create an object called car
with properties like make
, model
, and year
. Add a method called start
that prints “Engine started!”.
Day 10: DOM Basics
The Document Object Model (DOM) is how JavaScript interacts with HTML. Let’s learn how to grab and change HTML elements.
Selecting Elements
Use document.getElementById()
to grab an HTML element by its id
.
Example:
<p id="demo">Hello</p>
<script>
let element = document.getElementById("demo");
console.log(element.innerHTML); // Output: Hello
</script>
Changing Element Content
You can change the content of an element using innerHTML
.
Example:
<p id="demo">Hello</p>
<script>
let element = document.getElementById("demo");
element.innerHTML = "Hi!";
</script>
Handling Events
You can make your page respond to user actions (like clicks) using event listeners.
Example:
<button id="myButton">Click Me</button>
<script>
let button = document.getElementById("myButton");
button.addEventListener("click", function() {
alert("Button clicked!");
});
</script>
Try This: Create a button that changes the text of a paragraph when clicked.
Day 11: Arrays (Advanced)
Today, we’ll learn some advanced array methods that make working with arrays easier.
Adding and Removing Items
push()
: Adds an item to the end of an array.pop()
: Removes the last item from an array.unshift()
: Adds an item to the beginning of an array.shift()
: Removes the first item from an array.
Example:
let fruits = ["Apple", "Banana"];
fruits.push("Mango"); // ["Apple", "Banana", "Mango"]
fruits.pop(); // ["Apple", "Banana"]
fruits.unshift("Grapes"); // ["Grapes", "Apple", "Banana"]
fruits.shift(); // ["Apple", "Banana"]
Finding Items
indexOf()
: Finds the index of an item.includes()
: Checks if an item exists in the array.
Example:
let cities = ["Dehradun", "Haldwani", "Delhi"];
console.log(cities.indexOf("Haldwani")); // Output: 1
console.log(cities.includes("Nepal")); // Output: false
Try This: Create an array of your favorite cities and add a new city using push()
. Then check if “Delhi” exists in the array.
Day 12: Loops (While Loop)
Today, we’ll learn about the while
loop, which keeps running as long as a condition is true.
While Loop Syntax
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
- This loop will print numbers from 0 to 4.
Looping Until a Condition is Met
You can use a while
loop to keep asking for input until the user gives a valid response.
Example:
let answer = "";
while (answer !== "India") {
answer = prompt("Which country is Mount Everest in?");
}
console.log("Correct! Mount Everest is in Nepal.");
Try This: Write a while
loop that prints numbers from 10 to 1.
Day 13: Functions (Advanced)
Today, we’ll learn about arrow functions and default parameters.
Arrow Functions
Arrow functions are a shorter way to write functions.
Example:
// Regular function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
console.log(add(5, 10)); // Output: 15
Default Parameters
You can set default values for function parameters.
Example:
function greet(name = "Lokesh") {
console.log("Hello, " + name);
}
greet(); // Output: Hello, Lokesh
greet("Deepak"); // Output: Hello, Deepak
Try This: Write an arrow function called multiply
that takes two numbers and returns their product. Use default values of 1 for both numbers.
Day 14: Objects (Advanced)
Today, we’ll learn about nested objects and object methods.
Nested Objects
Objects can contain other objects.
Example:
let person = {
name: "Neha",
address: {
city: "Dehradun",
country: "India"
}
};
console.log(person.address.city); // Output: Dehradun
Object Methods
You can add functions (methods) to objects.
Example:
let person = {
name: "Vishal",
greet: function() {
console.log("Hello, " + this.name);
}
};
person.greet(); // Output: Hello, Vishal
Try This: Create an object called car
with properties like make
, model
, and year
. Add a method called start
that prints “Engine started!”.
Day 15: DOM Manipulation
Today, we’ll learn how to change the style and attributes of HTML elements using JavaScript.
Changing Styles
You can change the style of an element using the style
property.
Example:
<p id="demo">Hello</p>
<script>
let element = document.getElementById("demo");
element.style.color = "blue";
element.style.fontSize = "20px";
</script>
Changing Attributes
You can change attributes like src
, href
, etc., using the setAttribute()
method.
Example:
<img id="myImage" src="old.jpg">
<script>
let image = document.getElementById("myImage");
image.setAttribute("src", "new.jpg");
</script>
Creating New Elements
You can create new HTML elements and add them to the page.
Example:
<div id="container"></div>
<script>
let newElement = document.createElement("p");
newElement.innerHTML = "This is a new paragraph!";
document.getElementById("container").appendChild(newElement);
</script>
Try This: Create a button that changes the background color of a paragraph when clicked.
Day 16: Events
Events are actions that happen on a webpage, like clicking a button, hovering over an element, or pressing a key. JavaScript can listen for these events and respond to them.
Adding Event Listeners
Use addEventListener()
to listen for events.
Example:
<button id="myButton">Click Me</button>
<script>
let button = document.getElementById("myButton");
button.addEventListener("click", function() {
alert("Button clicked by Vishal!");
});
</script>
Common Events
click
: When an element is clicked.mouseover
: When the mouse hovers over an element.keydown
: When a key is pressed.
Example:
<p id="demo">Hover over me!</p>
<script>
let paragraph = document.getElementById("demo");
paragraph.addEventListener("mouseover", function() {
paragraph.style.color = "red";
});
</script>
Try This: Create a button that changes the text of a paragraph when clicked.
Day 17: Forms
Forms are used to collect user input. JavaScript can help validate and process form data.
Accessing Form Data
You can access form data using the value
property.
Example:
<form id="myForm">
<input type="text" id="name" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>
<script>
let form = document.getElementById("myForm");
form.addEventListener("submit", function(event) {
event.preventDefault(); // Prevents the form from submitting
let name = document.getElementById("name").value;
alert("Hello, " + name + "!");
});
</script>
Form Validation
You can check if the user has entered valid data before submitting the form.
Example:
<form id="myForm">
<input type="email" id="email" placeholder="Enter your email">
<button type="submit">Submit</button>
</form>
<script>
let form = document.getElementById("myForm");
form.addEventListener("submit", function(event) {
event.preventDefault();
let email = document.getElementById("email").value;
if (email.includes("@")) {
alert("Valid email!");
} else {
alert("Invalid email!");
}
});
</script>
Try This: Create a form that asks for the user’s city (use Dehradun, Haldwani) and displays a message like “Welcome to [city]!”.
Day 18: Error Handling
Sometimes, things go wrong in your code. Error handling helps you deal with those situations gracefully.
Try…Catch
Use try...catch
to handle errors.
Example:
try {
let x = 10;
let y = x.toUpperCase(); // This will throw an error
} catch (error) {
console.log("An error occurred: " + error.message);
}
Throwing Custom Errors
You can throw your own errors using throw
.
Example:
let age = 15;
try {
if (age < 18) {
throw "You must be 18 or older!";
}
} catch (error) {
console.log(error); // Output: You must be 18 or older!
}
Try This: Write a function that divides two numbers. If the second number is 0, throw an error saying “Cannot divide by zero!”.
Day 19: Local Storage
Local storage allows you to save data in the user’s browser. This data stays even after the browser is closed.
Saving Data
Use localStorage.setItem()
to save data.
Example:
localStorage.setItem("name", "Neha");
Retrieving Data
Use localStorage.getItem()
to retrieve data.
Example:
let name = localStorage.getItem("name");
console.log(name); // Output: Neha
Removing Data
Use localStorage.removeItem()
to delete data.
Example:
localStorage.removeItem("name");
Try This: Create a form that saves the user’s name in local storage and displays it when the page loads.
Day 20: Fetch API
The Fetch API is used to make HTTP requests (like getting data from a server).
Fetching Data
Use fetch()
to get data from a URL.
Example:
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log("Error: " + error));
Displaying Data
You can display the fetched data on your webpage.
Example:
<ul id="userList"></ul>
<script>
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(data => {
let userList = document.getElementById("userList");
data.forEach(user => {
let li = document.createElement("li");
li.textContent = user.name;
userList.appendChild(li);
});
})
.catch(error => console.log("Error: " + error));
</script>
Try This: Fetch a list of countries from an API (like https://restcountries.com/v3.1/all
) and display their names on the webpage.
Day 21: Classes
Classes are blueprints for creating objects. They help you organize your code in a more structured way.
Creating a Class
Use the class
keyword to create a class.
Example:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
}
let neha = new Person("Neha", 25);
neha.greet(); // Output: Hello, my name is Neha and I'm 25 years old.
Inheritance
You can create a new class that inherits from another class using extends
.
Example:
class Student extends Person {
constructor(name, age, grade) {
super(name, age); // Calls the parent class constructor
this.grade = grade;
}
study() {
console.log(`${this.name} is studying in grade ${this.grade}.`);
}
}
let vishal = new Student("Vishal", 20, 12);
vishal.greet(); // Output: Hello, my name is Vishal and I'm 20 years old.
vishal.study(); // Output: Vishal is studying in grade 12.
Try This: Create a class called Car
with properties like make
, model
, and year
. Add a method called start
that prints “Engine started!”.
Day 22: Modules
Modules help you split your code into separate files, making it easier to manage and reuse.
Exporting and Importing
- Use
export
to make a function or variable available in other files. - Use
import
to use that function or variable.
Example:
- Create a file called
math.js
:
export function add(a, b) {
return a + b;
}
export const PI = 3.14;
- In your main file (e.g.,
main.js
):
import { add, PI } from './math.js';
console.log(add(5, 10)); // Output: 15
console.log(PI); // Output: 3.14
Try This: Create a module called greet.js
that exports a function to greet a user. Import and use it in your main file.
Day 23: Timers
JavaScript has built-in functions to delay or repeat code execution.
setTimeout
Runs a function once after a specified delay (in milliseconds).
Example:
setTimeout(() => {
console.log("Hello after 3 seconds!");
}, 3000);
setInterval
Repeats a function at a specified interval.
Example:
let count = 0;
let interval = setInterval(() => {
console.log("Count: " + count);
count++;
if (count > 5) {
clearInterval(interval); // Stops the interval
}
}, 1000);
Try This: Create a timer that displays a message every 5 seconds and stops after 20 seconds.
Day 24: Regular Expressions
Regular expressions (regex) are patterns used to match and manipulate strings.
Creating a Regex
Use /pattern/
to create a regex.
Example:
let text = "Hello, my email is lokesh@example.com.";
let emailRegex = /\S+@\S+\.\S+/; // Matches an email address
console.log(emailRegex.test(text)); // Output: true
Common Regex Methods
test()
: Checks if a string matches the regex.match()
: Finds all matches in a string.
Example:
let phoneRegex = /\d{10}/; // Matches a 10-digit phone number
let phone = "1234567890";
console.log(phoneRegex.test(phone)); // Output: true
Try This: Write a regex to check if a string is a valid date in the format DD-MM-YYYY
.
Day 25: Working with Dates
JavaScript has a Date
object to work with dates and times.
Creating a Date
Use the Date
constructor to create a date.
Example:
let today = new Date();
console.log(today); // Output: Current date and time
Formatting Dates
You can get specific parts of a date (like day, month, year).
Example:
let birthday = new Date(1995, 11, 17); // December 17, 1995
console.log(birthday.getFullYear()); // Output: 1995
console.log(birthday.getMonth() + 1); // Output: 12 (months are 0-based)
console.log(birthday.getDate()); // Output: 17
Calculating Differences
You can calculate the difference between two dates.
Example:
let today = new Date();
let birthday = new Date(1995, 11, 17);
let ageInMilliseconds = today - birthday;
let ageInYears = Math.floor(ageInMilliseconds / (1000 * 60 * 60 * 24 * 365));
console.log("Age: " + ageInYears); // Output: Age: [calculated age]
Try This: Create a program that calculates how many days are left until your next birthday.
Day 26: Promises
Promises are used to handle asynchronous operations (like fetching data). They make it easier to manage code that runs in the background.
Creating a Promise
Use the Promise
constructor to create a promise.
Example:
let promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Operation successful!");
} else {
reject("Operation failed!");
}
});
promise
.then(result => console.log(result)) // Output: Operation successful!
.catch(error => console.log(error));
Fetching Data with Promises
You can use promises with the Fetch API.
Example:
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log("Error: " + error));
Try This: Create a promise that resolves after 2 seconds and prints “Done!”.
Day 27: Async/Await
async/await
is a modern way to handle asynchronous code. It makes your code look cleaner and easier to read.
Using Async/Await
- Use
async
before a function to make it return a promise. - Use
await
to wait for a promise to resolve.
Example:
async function fetchData() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/users");
let data = await response.json();
console.log(data);
} catch (error) {
console.log("Error: " + error);
}
}
fetchData();
Try This: Rewrite the promise example from Day 26 using async/await
.
Day 28: Destructuring
Destructuring allows you to extract values from arrays or objects into variables.
Array Destructuring
Example:
let fruits = ["Apple", "Banana", "Mango"];
let [first, second, third] = fruits;
console.log(first); // Output: Apple
console.log(second); // Output: Banana
Object Destructuring
Example:
let person = { name: "Sumit", age: 30, city: "Dehradun" };
let { name, age } = person;
console.log(name); // Output: Sumit
console.log(age); // Output: 30
Try This: Destructure an array of numbers and calculate their sum.
Day 29: Spread and Rest Operators
The spread operator (...
) and rest operator (...
) are powerful tools for working with arrays and objects.
Spread Operator
Used to expand an array or object.
Example:
let numbers = [1, 2, 3];
let newNumbers = [...numbers, 4, 5];
console.log(newNumbers); // Output: [1, 2, 3, 4, 5]
Rest Operator
Used to collect multiple elements into an array.
Example:
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // Output: 10
Try This: Use the spread operator to merge two objects.
Day 30: Basic Project + Project Suggestions
It’s time to put everything you’ve learned into practice! Let’s build a basic project and then I’ll suggest more projects for you to try.
Project: To-Do List
Create a simple to-do list where users can add and remove tasks.
HTML:
<div id="app">
<h1>To-Do List</h1>
<input type="text" id="taskInput" placeholder="Add a new task">
<button id="addTask">Add Task</button>
<ul id="taskList"></ul>
</div>
JavaScript:
let taskInput = document.getElementById("taskInput");
let addTask = document.getElementById("addTask");
let taskList = document.getElementById("taskList");
addTask.addEventListener("click", function() {
let task = taskInput.value;
if (task) {
let li = document.createElement("li");
li.textContent = task;
taskList.appendChild(li);
taskInput.value = ""; // Clear the input
}
});
taskList.addEventListener("click", function(event) {
if (event.target.tagName === "LI") {
event.target.remove(); // Remove the task
}
});
How It Works:
- Users can type a task in the input box and click “Add Task” to add it to the list.
- Clicking on a task removes it from the list.
Try This: Add a feature to mark tasks as completed (e.g., strikethrough the text).
Project Suggestions
Here are some more projects to practice and improve your skills:
- Calculator: Build a basic calculator that can add, subtract, multiply, and divide.
- Weather App: Fetch weather data from an API and display it on a webpage.
- Quiz App: Create a quiz with multiple-choice questions and display the score at the end.
- Expense Tracker: Build an app to track income and expenses, and display the balance.
- Countdown Timer: Create a timer that counts down to a specific date and time.
- Random Quote Generator: Fetch random quotes from an API and display them on a webpage.
- Portfolio Website: Build a personal portfolio website using HTML, CSS, and JavaScript.
- Rock Paper Scissors Game: Create a simple game where the user plays against the computer.
- Chat App: Build a basic chat app using Firebase or another backend service.
- E-commerce Cart: Create a simple product listing with a shopping cart feature.
Final Words
Congratulations on completing the 30-Days of JavaScript Mastery.
You’ve learned the basics of JavaScript and built a small project. Now, it’s time to keep practicing and build more projects. The more you code, the better you’ll get.
Remember:
- Practice daily.
- Break problems into smaller steps.
- Don’t be afraid to make mistakes.
Happy coding!