Part 1: JavaScript Foundations
Welcome to the JavaScript Masterclass.
JavaScript is one of the most important programming
languages used on the web.
What is JavaScript?
JavaScript is a programming language that allows
developers to add logic, interaction and dynamic
behavior to webpages and applications.
HTML vs CSS vs JavaScript
| Technology |
Purpose |
| HTML |
Structure |
| CSS |
Design and presentation |
| JavaScript |
Logic and interaction |
Adding JavaScript to HTML
Internal JavaScript
<script>
console.log("Hello World!");
External JavaScript
<script src="script.js"></script>
Your First JavaScript Program
console.log("Hello World!");
Comments
// Single-line comment
/*
Multi-line comment
*/
Part 1 Challenge
- Create an HTML file.
- Create a file named
script.js.
- Connect JavaScript with HTML.
- Print your name using
console.log().
- Print your favorite subject.
Part 2: Variables & Data Types
What is a Variable?
A variable is a named location used to store
a value that a program can work with.
let
let age = 15;
age = 16;
const
const country = "India";
var
var name = "Rahul";
Modern JavaScript generally prefers
let and const.
Primitive Data Types
- String
- Number
- BigInt
- Boolean
- Undefined
- Null
- Symbol
Examples
let name = "Somil";
let age = 15;
let isStudent = true;
let score;
let result = null;
typeof Operator
console.log(typeof "Hello");
console.log(typeof 100);
console.log(typeof true);
Part 3: Operators & Expressions
Arithmetic Operators
let a = 10;
let b = 3;
console.log(a + b);
console.log(a - b);
console.log(a * b);
console.log(a / b);
console.log(a % b);
console.log(a ** b);
Assignment Operators
let x = 10;
x += 5;
x -= 2;
x *= 3;
x /= 2;
Comparison Operators
console.log(10 > 5);
console.log(10 < 5);
console.log(10 === 10);
console.log(10 !== 5);
Logical Operators
let age = 18;
console.log(age >= 18 && age <= 60);
console.log(age < 18 || age > 60);
console.log(!(age < 18));
Operator Precedence
let result = 10 + 5 * 2;
Use parentheses when you want to make
the intended order of operations explicit.
Part 4: Conditions
if Statement
let age = 18;
if (age >= 18) {
console.log("Adult");
}
if...else
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
else if
let marks = 85;
if (marks >= 90) {
console.log("Excellent");
} else if (marks >= 75) {
console.log("Very Good");
} else {
console.log("Keep Practicing");
}
Switch
let day = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Unknown day");
}
Ternary Operator
let age = 18;
let result =
age >= 18 ? "Adult" : "Minor";
Part 5: Loops
Loops allow a program to execute a block of code
repeatedly.
for Loop
for (let i = 1; i <= 5; i++) {
console.log(i);
}
while Loop
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
do...while
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
break
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}
continue
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue;
}
console.log(i);
}
Part 6: Functions
Functions are reusable blocks of code designed
to perform a particular task.
Function Declaration
function greet() {
console.log("Hello!");
}
greet();
Parameters
function greet(name) {
console.log("Hello " + name);
}
greet("Rahul");
Return Value
function add(a, b) {
return a + b;
}
let result = add(10, 20);
console.log(result);
Arrow Functions
const add = (a, b) => {
return a + b;
};
Short Arrow Function
const square = number => number * number;
Part 7: Arrays
Arrays store multiple values in a single collection.
Creating an Array
let fruits = [
"Apple",
"Mango",
"Banana"
];
Accessing Elements
console.log(fruits[0]);
Adding Elements
fruits.push("Orange");
Removing Elements
fruits.pop();
Important Array Methods
- push()
- pop()
- shift()
- unshift()
- slice()
- splice()
- includes()
- indexOf()
- find()
- filter()
- map()
- reduce()
- forEach()
map()
let numbers = [1, 2, 3, 4];
let doubled =
numbers.map(number => number * 2);
filter()
let numbers = [10, 15, 20, 25];
let result =
numbers.filter(number => number >= 20);
reduce()
let numbers = [10, 20, 30];
let total =
numbers.reduce(
(sum, number) => sum + number,
0
);
Part 8: Objects
Objects store related data and functionality
using properties and methods.
Creating an Object
const student = {
name: "Rahul",
age: 16,
grade: 10
};
Accessing Properties
console.log(student.name);
console.log(student["age"]);
Methods
const user = {
name: "Rahul",
greet() {
console.log("Hello!");
}
};
user.greet();
Destructuring
const student = {
name: "Rahul",
age: 16
};
const { name, age } = student;
Spread Operator
const first = {
name: "Rahul"
};
const second = {
age: 16
};
const student = {
...first,
...second
};
Part 9: Strings, Numbers & Dates
String Methods
let text = "JavaScript";
console.log(text.length);
console.log(text.toUpperCase());
console.log(text.toLowerCase());
console.log(text.includes("Script"));
console.log(text.slice(0, 4));
Template Literals
let name = "Rahul";
let message =
`Hello ${name}!`;
console.log(message);
Math
console.log(Math.round(4.6));
console.log(Math.floor(4.9));
console.log(Math.ceil(4.1));
console.log(Math.max(10, 20, 30));
console.log(Math.min(10, 20, 30));
console.log(Math.random());
Dates
const today = new Date();
console.log(today);
console.log(today.getFullYear());
console.log(today.getMonth());
console.log(today.getDate());
Part 10: DOM Manipulation
The DOM, or Document Object Model, represents
the structure of an HTML document as objects
that JavaScript can access and modify.
Selecting an Element
const heading =
document.querySelector("h1");
Selecting by ID
const title =
document.getElementById("title");
Changing Text
heading.textContent =
"New Heading";
Changing HTML
element.innerHTML =
"<strong>Hello</strong>";
Changing Styles
element.style.color = "red";
element.style.fontSize = "30px";
Creating an Element
const paragraph =
document.createElement("p");
paragraph.textContent =
"New paragraph";
document.body.appendChild(paragraph);
Part 11: Events & User Interaction
Events allow JavaScript to respond to actions
performed by users or the browser.
Click Event
button.addEventListener(
"click",
function () {
console.log("Button clicked!");
}
);
Input Event
input.addEventListener(
"input",
function () {
console.log(input.value);
}
);
Common Events
- click
- dblclick
- input
- change
- submit
- keydown
- keyup
- mouseover
- mouseout
- load
Preventing Form Submission
form.addEventListener(
"submit",
function (event) {
event.preventDefault();
}
);
Part 12: Modern JavaScript
let and const
Modern JavaScript code generally uses
let and const
instead of relying on var.
Destructuring
const user = {
name: "Rahul",
age: 18
};
const { name, age } = user;
Spread Syntax
const numbers = [1, 2, 3];
const newNumbers = [
...numbers,
4,
5
];
Rest Parameters
function add(...numbers) {
return numbers.reduce(
(sum, number) => sum + number,
0
);
}
Optional Chaining
console.log(user?.address?.city);
Nullish Coalescing
const username =
user.name ?? "Guest";
Part 13: Asynchronous JavaScript
Asynchronous programming allows JavaScript to work
with operations that may finish later without
unnecessarily blocking the rest of the program.
setTimeout()
setTimeout(() => {
console.log("Executed later");
}, 2000);
Promises
const promise = new Promise(
(resolve, reject) => {
resolve("Success!");
}
);
async / await
async function getData() {
const result =
await promise;
console.log(result);
}
Why Async JavaScript Matters
- API requests
- Network operations
- Timers
- File operations
- Server communication
Part 14: APIs & JSON
What is an API?
An API allows different software systems to communicate
and exchange data through defined interfaces.
JSON
{
"name": "Rahul",
"age": 18,
"student": true
}
fetch()
fetch("https://example.com/data")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
Using async / await with fetch
async function loadData() {
try {
const response =
await fetch(
"https://example.com/data"
);
const data =
await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
Part 15: Error Handling & Debugging
try...catch
try {
riskyFunction();
} catch (error) {
console.error(error);
}
throw
function divide(a, b) {
if (b === 0) {
throw new Error(
"Cannot divide by zero"
);
}
return a / b;
}
finally
try {
console.log("Trying");
} catch (error) {
console.log("Error");
} finally {
console.log("Finished");
}
Console Debugging
console.log("Debug message");
console.warn("Warning");
console.error("Error");
console.table([
{ name: "Rahul", age: 18 },
{ name: "Aman", age: 17 }
]);
Part 16: Advanced JavaScript
Scope
Scope determines where variables can be accessed
within a JavaScript program.
Closures
function counter() {
let count = 0;
return function () {
count++;
return count;
};
}
const increment =
counter();
console.log(increment());
console.log(increment());
Higher-Order Functions
A higher-order function can receive another function
as an argument or return a function.
function calculate(
a,
b,
operation
) {
return operation(a, b);
}
const result = calculate(
10,
5,
(a, b) => a + b
);
Classes
class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
introduce() {
console.log(
`My name is ${this.name}`
);
}
}
const student =
new Student("Rahul", 18);
student.introduce();
Modules
// math.js
export function add(a, b) {
return a + b;
}
// app.js
import { add }
from "./math.js";
Part 17: Real World JavaScript Projects
Programming is best learned by building.
Use the following projects to turn concepts
into practical skills.
Project 1: Counter App
Create buttons that increase, decrease and reset
a number using JavaScript.
Project 2: Digital Clock
Build a live clock using the Date object
and timers.
Project 3: Calculator
Build a calculator using HTML, CSS and JavaScript.
Project 4: To-Do List
Create, complete and delete tasks using
DOM manipulation.
Project 5: Quiz Application
Create multiple-choice questions,
track answers and calculate scores.
Project 6: Weather Application
Build an application that retrieves weather
information from an API.
Project 7: Expense Tracker
Store income and expenses and calculate
the current balance.
Project 8: Notes Application
Create, edit and delete notes using
browser storage.
Final Challenge
Build a complete JavaScript-powered website
containing:
- Navigation
- Interactive buttons
- Form validation
- Dynamic content
- DOM manipulation
- Local storage
- API integration
- Error handling
- Responsive interface
JavaScript Quick Cheat Sheet
Important JavaScript Concepts
| Concept |
Purpose |
| let |
Block-scoped variable |
| const |
Block-scoped binding that cannot be reassigned |
| function |
Reusable block of code |
| Array |
Collection of values |
| Object |
Collection of related properties |
| if |
Conditional execution |
| for |
Repeated execution |
| map() |
Transform array elements |
| filter() |
Select matching elements |
| reduce() |
Combine values into one result |
| querySelector() |
Select DOM elements |
| addEventListener() |
Listen for events |
| Promise |
Represent an eventual asynchronous result |
| async / await |
Work with promises using readable syntax |
| fetch() |
Make network requests |
| try / catch |
Handle runtime errors |
JavaScript Frequently Asked Questions
Is JavaScript the same as Java?
No. JavaScript and Java are separate programming
languages with different designs and ecosystems.
Can JavaScript be used outside the browser?
Yes. JavaScript can also run in environments
such as servers and other JavaScript runtimes.
Should beginners learn HTML and CSS before JavaScript?
Learning basic HTML and CSS first is helpful
for frontend development because JavaScript
often interacts with HTML and CSS.
What should I build after learning JavaScript?
Start with small projects such as counters,
calculators and to-do lists, then progress
toward API-based applications and larger projects.