JavaScript
Phase - 1
1. Introduction to JavaScript
What is JavaScript?
JavaScript is a programming language used to make web pages interactive.
Role in Web Development:
HTML → Structure
CSS → Styling
JavaScript → Functionality
How JS works in browser:
Can manipulate HTML (DOM)
Example:
alert("Hello World");
2. Setting up Environment
Ways to run JS:
Browser Console
VS Code
[Link]
Link JS with HTML:
<script src="[Link]"></script>
3. DOM (Document Object Model)
What is DOM?
The DOM is a tree-like structure of your HTML page that JavaScript can access and
modify.
👉 Browser converts HTML into an object structure:
<h1 id="title">Hi</h1>
becomes:
document
└── h1 (id="title")
Accessing Elements
[Link]("title")
// Finds element with id="title"
Changing Content
[Link]("title").innerText = "Hello";
✔ Changes visible text
✔ Updates UI instantly
Other Ways to Select Elements
By Class
[Link]("box");
By Tag
[Link]("p");
Modern (Most Used)
[Link]("#title"); // single
[Link](".box"); // multiple
Changing HTML & Styles
Change HTML
[Link] = "<b>Hello</b>";
Change CSS
[Link] = "red";
[Link] = "yellow";
Create & Add Elements
let newEl = [Link]("p");
[Link] = "New Paragraph";
[Link](newEl);
Remove Element
[Link]();
4. Events in JavaScript
What is an Event?
An event is an action performed by the user or browser.
Examples:
Click
Typing
Hover
Submit
Example
[Link]("click", () => {
alert("Clicked");
});
Breakdown:
button → selected element
addEventListener → listens for event
"click" → event type
() => {} → function to run
Common Events
Event Description
click User clicks
mouseover Hover
mouseout Leave
keydown Key pressed
submit Form submit
change Input change
Example: Click Event
let btn = [Link]("button");
[Link]("click", () => {
[Link]("Button clicked");
});
Event with Parameters
[Link]("click", (event) => {
[Link](event);
});
✔ event object gives extra info:
mouse position
target element
Change DOM Using Event
[Link]("click", () => {
[Link] = "black";
});
3. Variables in JavaScript
1. var (Old Way – Function Scoped)
Key Points:
Function scoped (NOT block scoped)
Can be redeclared
Can be updated
Hoisted (initialized as undefined)
Example 1: Redeclaration Allowed
var a = 10;
var a = 20;
[Link](a); // 20
Example 2: Function Scope
function test() {
var x = 100;
}
[Link](x); // ❌ Error
👉 Because x is inside function → not accessible outside
Example 3: NOT Block Scoped (Important)
if (true) {
var y = 50;
}
[Link](y); // ✅ 50
👉 Even inside {} block → still accessible
⚠️ This is why var is unsafe
Example 4: Hoisting
[Link](a); // undefined
var a = 10;
👉 JS internally does:
var a;
[Link](a);
a = 10;
2. let (Modern – Block Scoped)
Key Points:
Block scoped ({})
Cannot be redeclared
Can be updated
Hoisted but NOT initialized (Temporal Dead Zone)
Example 1: No Redeclaration
let a = 10;
let a = 20; // ❌ Error
Example 2: Block Scope
if (true) {
let x = 100;
}
[Link](x); // ❌ Error
👉 x only exists inside block
Example 3: Can Update
let a = 10;
a = 20;
[Link](a); // 20
Example 4: Temporal Dead Zone (Very Important)
[Link](a); // ❌ Error
let a = 10;
👉 Unlike var, it does NOT become undefined
👉 It stays in TDZ (Temporal Dead Zone) until declared
3. const (Constant – Most Strict)
Key Points:
Block scoped
Cannot be redeclared
Cannot be updated
Must be initialized at declaration
Example 1: Must Assign Value
const a; // ❌ Error
Example 2: Cannot Update
const a = 10;
a = 20; // ❌ Error
Example 3: Block Scope
if (true) {
const x = 100;
}
[Link](x); // ❌ Error
Example 4: Objects & Arrays (Important Twist)
const obj = { name: "Aqib" };
[Link] = "Ali"; // ✅ Allowed
[Link](obj);
👉 You can modify inside, but cannot reassign:
obj = {}; // ❌ Error
Final Comparison Table
Feature var let const
Scope Function Block Block
Redeclare Yes No No
Update Yes Yes No
Hoisting Yes Yes Yes
TDZ No Yes Yes
5. Data Types
What is a Data Type?
A data type tells JavaScript what kind of value a variable is storing.
let name = "Aqib"; // string
let age = 22; // number
Types of Data in JavaScript
JavaScript has 2 main categories:
1. Primitive Data Types
👉 Simple, single values (stored directly in memory)
2. Non-Primitive Data Types
👉 Complex data (stored by reference)
1. Primitive Data Types
1. String
👉 Used to store text
let name = "Hello";
let city = 'Mumbai';
Features:
Written inside " " or ' '
Can use template literals:
let name = "Aqib";
[Link](`Hello ${name}`);
2. Number
👉 Used for numbers (integer + decimal)
let age = 22;
let price = 99.99;
Special values:
Infinity
-Infinity
NaN // Not a Number
Example:
[Link]("abc" * 2); // NaN
3. Boolean
👉 True or False values
let isLoggedIn = true;
let isAdmin = false;
Used in conditions:
if (isLoggedIn) {
[Link]("Welcome");
}
4. Undefined
👉 Variable declared but not assigned
let x;
[Link](x); // undefined
5. Null
👉 Intentional empty value
let data = null;
Difference:
undefined → JS didn’t assign value
null → YOU intentionally set empty value
⚠️ Important:
typeof null // "object" ❌ (JS bug)
2. Non-Primitive Data Types
👉 These store multiple values or complex data
1. Object
👉 Collection of key-value pairs
let user = {
name: "John",
age: 25
};
Access values:
[Link]([Link]); // John
[Link](user["age"]); // 25
Real Use Case:
let product = {
title: "Phone",
price: 20000,
inStock: true
};
2. Array
Used to store multiple values in a list
let arr = [1, 2, 3];
Access elements:
[Link](arr[0]); // 1
[Link](arr[1]); // 2
Mixed Data:
let data = [1, "Hello", true];
Key Difference
Feature Primitive Non-Primitive
Storage Value Reference
Example Number, String Object, Array
Copy Behavior Copy Reference
6. Data Type Conversion
Implicit Conversion (Type Coercion)
This is done automatically by JavaScript when it thinks conversion is needed.
Example:
"5" + 2 // "52"
Why?
"5" is a string
2 is a number
When + is used and one operand is a string, JS converts the number → string
2. Explicit Conversion (Type Casting)
This is when you manually convert data types.
1. Convert to Number
Number("5") // 5
More:
Number("10.5") // 10.5
Number(true) // 1
Number(false) // 0
Number("abc") // NaN ❌
2. Convert to String
String(10) // "10"
(10).toString() // "10"
3. Convert to Boolean
Boolean(1) // true
Boolean(0) // false
Boolean("") // false
Boolean("Hi") // true
7. Comparison Operators
== vs ===
== → checks value
=== → checks value + type
Example:
5 == "5" // true
5 === "5" // false
Phase – 2
8. Control Flow (if/else, switch)
What is Control Flow?
Control flow means how your code makes decisions and runs different parts based on
conditions.
👉 In simple words:
“If something is true → do this, otherwise → do something else”
1. if / else Statement
Basic Syntax:
if (condition) {
// runs if condition is true
} else {
// runs if condition is false
}
Example 1: Simple if/else
let age = 18;
if (age >= 18) {
[Link]("Adult");
} else {
[Link]("Minor");
}
👉 Output: Adult
How it works:
1. Check condition → age >= 18
2. If TRUE → run if block
3. If FALSE → run else block
Example 2: Only if (No else)
let temp = 30;
if (temp > 25) {
[Link]("Hot weather");
}
👉 If condition false → nothing happens
Example 3: Multiple Conditions (else if)
let marks = 75;
if (marks >= 90) {
[Link]("A Grade");
} else if (marks >= 70) {
[Link]("B Grade");
} else if (marks >= 50) {
[Link]("C Grade");
} else {
[Link]("Fail");
}
Flow of above code:
Checks one by one
Stops when first TRUE condition is found
Important Concepts
1. Comparison Operators
> < >= <= == === !=
2. Logical Operators
&& (AND)
|| (OR)
! (NOT)
Example:
let age = 20;
let hasID = true;
if (age >= 18 && hasID) {
[Link]("Allowed");
}
Nested if
let age = 20;
if (age >= 18) {
if (age >= 60) {
[Link]("Senior");
} else {
[Link]("Adult");
}
}
2. switch Statement
👉 Used when you have multiple fixed values
Syntax:
switch (value) {
case value1:
// code
break;
case value2:
// code
break;
default:
// default code
}
Example 1:
let day = 2;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
default:
[Link]("Invalid day");
}
👉 Output: Tuesday
⚠️ Important: break keyword
👉 break stops execution
Without break:
let day = 1;
switch (day) {
case 1:
[Link]("Monday");
case 2:
[Link]("Tuesday");
}
👉 Output:
Monday
Tuesday
👉 This is called fall-through
Example 2: Multiple cases
let fruit = "apple";
switch (fruit) {
case "apple":
case "banana":
[Link]("Common fruit");
break;
default:
[Link]("Other fruit");
}
if/else vs switch
Feature if/else switch
Use case Conditions/ranges Fixed values
Flexibility More flexible Limited
Readability Medium Cleaner for cases
When to Use What?
👉 Use if/else when:
Checking ranges (age > 18)
Complex conditions
👉 Use switch when:
Fixed values (day = 1,2,3)
Menu systems
9. Strings in JavaScript
Methods:
let str = "Hello";
[Link](); // HELLO
Template Literals:
let name = "Aqib";
[Link](`Hello ${name}`);
10. Numbers & Math
[Link](); // random number
[Link](4.7); // 4
11. Date & Time
let date = new Date();
[Link]([Link]());
12. Arrays
What is an Array?
let arr = [1, 2, 3];
This creates an array with 3 elements.
Index starts from 0
So:
arr[0] // 1
arr[1] // 2
arr[2] // 3
Basic Methods
1. push() → Add element at end
[Link](4);
Result:
[1, 2, 3, 4]
2. pop() → Remove last element
[Link]();
Result:
[1, 2, 3]
3. Loop with forEach()
[Link](item => [Link](item));
Output:
1
2
3
✔ Runs a function for each element
✔ Doesn’t return a new array
Important Array Methods (Must Know)
1. Add / Remove Elements
unshift() → Add at beginning
[Link](0);
[0, 1, 2, 3]
shift() → Remove from beginning
[Link]();
[1, 2, 3]
2. Transform & Iterate
map() → Create new array
let newArr = [Link](item => item * 2);
[2, 4, 6]
✔ Returns a new array
filter() → Filter elements
let result = [Link](item => item > 1);
[2, 3]
reduce() → Single value result
let sum = [Link]((acc, curr) => acc + curr, 0);
6
3. Search Methods
find()
[Link](item => item > 1);
2 (first match)
includes()
[Link](2); // true
indexOf()
[Link](3); // 2
4. Modify Array
splice() → Add/remove elements
[Link](1, 1);
Removes 1 element at index 1
slice() → Copy part of array
[Link](0, 2);
[1, 2]
✔ Does NOT modify original array
5. Convert / Join
join()
[Link]("-");
"1-2-3"
toString()
[Link]();
"1,2,3"
Sorting
sort()
[Link]((a, b) => a - b);
reverse()
[Link]();
Looping Methods (Important)
for...of
for (let item of arr) {
[Link](item);
}
Normal for
for (let i = 0; i < [Link]; i++) {
[Link](arr[i]);
}
13. Objects
let user = {
name: "Aqib",
age: 22
};
[Link]([Link]);
14. Functions
1. Normal Function (Function Declaration)
function greet() {
return "Hello";
}
How it works:
function → keyword to define function
greet → function name
{} → function body
return → sends value back
Calling the function:
greet(); // "Hello"
Function with Parameters
function greet(name) {
return "Hello " + name;
}
greet("Aqib"); // Hello Aqib
Key Features
✔ Hoisted (can call before declaration)
✔ Has its own this
✔ Works in all situations
2. Arrow Function
const greet = () => "Hello";
How it works:
=> → arrow syntax
No function keyword
Short and clean
Arrow Function with Parameters
const greet = (name) => {
return "Hello " + name;
};
Short version:
const greet = name => "Hello " + name;
Differences Between Normal vs Arrow Function
Feature Normal Function Arrow Function
Syntax function greet(){} const greet = () => {}
Hoisting ✅ Yes ❌ No
this Own this Inherits from parent
Arguments object ✅ Available ❌ Not available
Use case General purpose Short callbacks
Important Concept: this
Normal Function:
const obj = {
name: "Aqib",
greet: function () {
[Link]([Link]);
}
};
[Link](); // Aqib
✔ this refers to the object
Arrow Function:
const obj = {
name: "Aqib",
greet: () => {
[Link]([Link]);
}
};
[Link](); // undefined ❌
❗ Arrow function does NOT have its own this
When to Use What?
Use Normal Function:
Object methods
When you need this
Constructor functions
Use Arrow Function:
Callbacks (map, filter, forEach)
Short functions
Functional programming
15. Scope & Execution Context
Global Scope
Local Scope
Example:
let a = 10;
function test() {
let b = 20;
}
16. Control Flow
if (age > 18) {
[Link]("Adult");
} else {
[Link]("Minor");
}
18. Truthy & Falsy Values
Falsy:
false
0
"", null, undefined
Example:
if ("hello") {
[Link]("Truthy");
}
19. DOM (Document Object Model)
[Link]("title").innerText = "Hello";
20. Events in JavaScript
[Link]("click", () => {
alert("Clicked");
});
21. Advanced Concepts
Hoisting:
[Link](a);
var a = 5;
Call Stack:
Tracks function execution
22. Asynchronous JavaScript
setTimeout(() => {
[Link]("Hello after 2 sec");
}, 2000);
Promises:
fetch("url")
.then(res => [Link]())
.then(data => [Link](data));
23. Error Handling
try {
let x = y;
} catch (err) {
[Link](err);
}
24. API & Fetch
fetch("[Link]
.then(res => [Link]())
.then(data => [Link](data));
25. Projects & Practice
Examples:
Calculator
To-Do App
Weather App