Full JavaScript Notes by Ritik Sir
Full JavaScript Notes by Ritik Sir
Introduction to JavaScript
JavaScript (JS) is a high-level, interpreted programming language used to
create interactive and dynamic web pages.
Runs directly in the browser
Also runs on servers ([Link])
Works with HTML and CSS
Supports object-oriented, functional, and event-driven programming
Initially created to make web pages interactive (buttons, forms, animations,
etc.)
History of JavaScript
Created in 1995 by Brendan Eich at Netscape
Originally called Mocha → LiveScript → JavaScript
Standardized as ECMAScript (ES)
Modern JavaScript versions: ES6 (2015) and later
Features of JavaScript
2|Page
JavaScript code is written inside the HTML file using the <script>
tag. Suitable for small to medium scripts used only on one page.
Syntax
<script>
JavaScript code
</script>
Example
<script>
let num1 = 10
let num2 = 20
[Link](num1 + num2)
</script>
Where to Place Internal Script?
Inside <head>
Inside <body> (Recommended)
📄 [Link]
Reusability No No Yes
Maintainability No No Yes
Variables in JavaScript
A variable is a container used to store data values in memory.
Why Variables Are Used?
Store data
Reuse values
Perform calculations
Handle user input
Control program flow
Function-scoped
Can be redeclared
Can be updated
Not recommended in modern JS
Characteristics of let
Block-scoped
Can be updated
Cannot be redeclared in the same scope
7|Page
Block-scoped
Cannot be updated
Cannot be redeclared
Must be initialized during declaration
Key Differences: var vs let vs const
Feature var let const
fruits[1] = "Orange";
JavaScript Array Methods
Array Purpose Example Output
Method
push() Add element at end let a=[1,2]; [1, 2, 3]
[Link](3);
pop() Remove last element let a=[1,2,3]; [1, 2]
[Link]();
unshift() Add element at beginning let a=[2,3]; [1, 2, 3]
[Link](1);
shift() Remove first element let a=[1,2,3]; [2, 3]
[Link]();
indexOf() Find index of element let a=[10,20,30]; 1
[Link](20);
includes() Check if element exists let a=[10,20,30]; false
[Link](25);
slice() Extract portion (no change let a=[1,2,3,4]; [2, 3]
to original) [Link](1,3);
join() Convert array to string let a=[1,2,3]; "1-2-3"
[Link]("-");
reverse() Reverse order of elements let a=[1,2,3]; [3, 2, 1]
[Link]();
sort() Sort elements let a=[3,1,2]; [1, 2, 3]
[Link]();
concat() Merge arrays let a=[1,2]; [1, 2, 3, 4]
[Link]([3,4]);
toString() Convert array to comma let a=[1,2,3]; "1,2,3"
string [Link]();
toSorted() Creates a sorted copy of let a = [‘A’,’Z’,’a’]
the array without changing [‘A’,’a’,’Z’];
the original. a. toSorted()
toReversed() Creates a reversed copy let a = [‘’Z’,’a’,’A’]
of the array without [‘A’,’a’,’Z’];
changing the original a. toReversed ()
Collection of properties
Each property has a key (name) and value
Values can be any data type
Stored by reference
Mutable (can be changed)
Object Syntax
let objectName = {
key1: value1,
key2: value2 };
Creating Objects
let person = {
name: "Shyam",
age: 25,
isStudent: true};
Accessing Object Properties
[Link]
person["age"]
from both
ends
slice(start,end) Extract part "Hello".slice(1,4) "ell"
of string
substring() Similar to "Hello".substring(1,4) "ell"
slice
replace() Replace "Hi "Hi
text Ram".replace("Ram","Shyam") Shyam"
includes() Check if "Hello".includes("lo") true
text exists
indexOf() Position of "Hello".indexOf("e") 1
text
split() Convert "a,b,c".split(",") ["a","b","c"]
string to
array
charAt() Character "Hello".charAt(1) "e"
at index
concat() Join strings "Hi".concat(" Ram") "Hi Ram"
Operators in JavaScript
Operators are symbols used to perform operations on variables and values.
Arithmetic Operators
Operator Meaning Example Output
+ Addition 5+2 7
- Subtraction 5-2 3
* Multiplication 5*2 10
14 | P a g e
Assignment Operators
Operator Meaning Example Result
= Assign x = 10 10
+= Add & assign x += 5 x=x+5
-= Subtract & assign x -= 3 x=x-3
*= Multiply & assign x *= 2 x=x*2
/= Divide & assign x /= 2 x=x/2
%= Modulus & assign x %= 3 Remainder
Comparison Operators
Operator Meaning Example Output
Logical Operators
Operator Meaning Example Output
// default block
}
switch Statement
Used when one value needs to be compared with multiple
possible values. Works well for menus, options, fixed cases.
Syntax
switch (expression) {
case value1:
// code
break;
default:
// if no case matches
}
Ternary Operator (Conditional Operator)
Short form of if...else.
Syntax
condition ? value_if_true : value_if_false
Example
let age = 18;
let result = age >= 18 ? "Adult" : "Minor";
for Loop
Used when the number of iterations is known.
Syntax
for (initialization; condition; update) {
// code block
}
How it works
Initialization → runs once
Condition → checked each time
Update → changes variable
while Loop
Runs while the condition is true.
Used when number of iterations is not known.
Syntax
while (condition) {
// code
}
do...while Loop
20 | P a g e
Functions in JavaScript
A function is a reusable block of code designed to perform a specific
task.
Functions help make programs modular, readable, and reusable.
Defined using the function keyword.
Avoid code repetition
Improve readability
Organize logic
Easy testing and maintenance
Reusable code blocks
Basic Syntax
function functionName(parameters) {
// code block
return value; // optional
21 | P a g e
}
Parameters vs Arguments
Term Meaning
Basic Syntax
Traditional Function
function functionName(parameters) {
return value;
}
Arrow Function Equivalent
Curly braces {} required when using multiple lines.
22 | P a g e
Examples
Example 1: Simple Addition
Normal Function
function add(a, b) {
return a + b;
}
Arrow Function
const add = (a, b) => {
return a + b;
};
Short Form
const add = (a, b) => a + b;
23 | P a g e
[Link](function(n) {
[Link](n);
24 | P a g e
});
Using Arrow Function
[Link](n => [Link](n));
map() Method
Creates a new array by applying a function to each element.
Returns a new transformed array
Does NOT change original array
Syntax
let newArray = [Link](function(element, index, array) {
return newValue;
});
Example
let nums = [1, 2, 3, 4];
[Link](squares);
Key Difference — map() vs forEach()
25 | P a g e
Modifies original No No
filter() Method
Returns elements that satisfy a condition.
let nums = [10, 15, 20, 25];
let result = [Link](n => n > 15);
[Link](result);
reduce() Method
Reduces array to a single value.
let nums = [1, 2, 3, 4];
let sum = [Link]((total, n) => total + n, 0);
[Link](sum);
find() Method
Returns first element that matches condition.
let nums = [5, 10, 15, 20];
let result = [Link](n => n > 10);
[Link](result);
26 | P a g e
some() Method
Checks if at least one element satisfies condition.
[1, 3, 5, 8].some(n => n % 2 === 0);
every() Method
Checks if all elements satisfy condition.
[2, 4, 6].every(n => n % 2 === 0);
Blocking
Sequential execution
Simple to understand
Can cause delays if task is slow
Example
[Link]("Start");
[Link]("Task 1");
[Link]("Task 2");
[Link]("End");
Asynchronous Programming
28 | P a g e
Non-blocking
Improves performance
Keeps UI responsive
Used for time-consuming tasks
[Link]("End");
Output
Start
End
Task 1
Where Asynchronous Programming is Used
API calls
File operations
Database queries
Timers
User input
Asynchronous Techniques in JavaScript
29 | P a g e
Callbacks
Promises
Async/Await
Synchronous vs Asynchronous
Feature Synchronous Asynchronous
Blocking Yes No
callback();
}
greet("Ram", function () {
[Link]("Welcome!");
});
What is Callback Hell?
When callbacks are nested inside callbacks repeatedly.
Example of Callback Hell
setTimeout(() => {
[Link]("Step 1");
setTimeout(() => {
[Link]("Step 2");
setTimeout(() => {
[Link]("Step 3");
setTimeout(() => {
[Link]("Step 4");
}, 1000);
}, 1000);
31 | P a g e
}, 1000);
}, 1000);
Structure
Step 1
Step 2
Step 3
Step 4
Deep nesting → hard to understand
Why Callback Hell is Bad?
Poor readability
Difficult debugging
Hard maintenance
Error handling becomes complex
Code reuse becomes difficult
32 | P a g e
Promises in JavaScript
A Promise is an object that represents the result of an asynchronous
operation that may complete now, later, or fail. Used to handle
asynchronous tasks more cleanly than callbacks.
Why Promises?
Creating a Promise
Syntax
let promise = new Promise(function(resolve, reject) {
// async operation
});
resolve() → success
reject() → failure
Example
let p = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Operation Successful");
} else {
reject("Operation Failed");
}
});
Consuming a Promise
Using .then() and .catch().
[Link](result => {
[Link](result);
}).catch(error => {
[Link](error);
35 | P a g e
});
Promise Chaining
Multiple asynchronous steps in sequence.
[Link](result => {
[Link](result);
return "Step 2";
})
.then(step2 => {
[Link](step2);
});
Each .then() receives previous result.
Finally Block
Runs regardless of success or failure.
[Link](() => {
[Link]("Operation completed");
});
36 | P a g e
Document
│
html
┌──────┴──────┐
<head > < body>
│ ┌───┴───┐
<Title> <h1> <p>
│ │ │
"My Page" "Hello" "Welcome to
DOM"
Types of Nodes
Node Type Example
Important Relationships
DOM works like a family tree
Parent Node → body is parent of h1 and p
Child Node → h1 is child of body
Sibling Node → h1 and p are siblings
Why DOM Tree is Important
39 | P a g e
getElementsByTagName()
40 | P a g e
querySelectorAll()
Selects all matching elements
let all = [Link](".demo");
all[1].[Link] = "green";
innerText
41 | P a g e
<p id="text"></p>
[Link]("text").innerText = "Hello";
Only visible text
textContent
[Link]("text").textContent = "Hello";
Includes hidden text too
createElement()
let p = [Link]("p");
[Link] = "New Paragraph";
appendChild()
[Link](p);
removeChild()
<ul id="myList">
<li id="item1">Item 1</li>
</ul>
let parent = [Link]("myList");
let child = [Link]("item1");
[Link](child);
Summary Table
Category Important Methods
43 | P a g e
DOM is Important
Without DOM:
Web pages would be static
No interactivity
No dynamic updates
With DOM:
Interactive websites
Real-time updates
Modern web apps
DOM vs HTML
HTML DOM
addEventListener in JavaScript
Event
44 | P a g e
User actions
Browser actions
Examples of Events
Mouse click
Key press
Page load
Form submit
Mouse hover
Input typing
addEventListener
addEventListener is a DOM method used to attach an event handler
to an element. When this event happens, run this function.
Why Use addEventListener()?
Parameter Description
event Event name (without "on")
45 | P a g e
Basic Example
HTML
<button id="btn">Click Me</button>
JavaScript
let btn = [Link]("btn")
[Link]("click", function() {
alert("Button clicked!");
});
How It Works
[Link]("click", sayHello);
Arrow Function
[Link]("click", () => {
alert("Arrow function");
});
[Link]("mouseout", () => {
[Link]("Mouse out");
});
addEventListener vs onclick
Feature addEventListener onclick
Browser window
URL
Tabs & navigation
History
Screen info
Dialog boxes
Browser details
BOM Hierarchy
window (Top Object)
├── document → DOM (Webpage)
├── location → URL info
├── history → Navigation history
├── navigator → Browser info
└── screen → Screen details
Everything in BOM starts from the window object
window Object (Global Object)
Represents the browser window/tab.
All global JavaScript objects, functions, and variables automatically
become members of window.
Window Object :
The window object represents a window in [Link] object of
window is created automatically by the browser. Window is the
object of browser, it is not the object of [Link] javascript
objects are string, array, date etc.
Methods of window object
49 | P a g e
alert() :
displays the alert box containing message with ok
button.
confirm() :
displays the confirm dialog box containing message
with ok
and cancel button.
prompt() :
displays a dialog box to get input from the user.
open() :
opens the new window.
<input type="button" value="Google"
onclick="Open()"/>
<script>
function Open(){
open('[Link]
}
</script>
setTimeout() :
JavaScript that allows you to execute a function or a block
of code after a specified delay (in milliseconds).
function greet(name) {
50 | P a g e
return name;
}
let result = greet('Ritik');
setTimeout ( () => {
[Link](result);
}, 3000);
availWidth :
[Link] ([Link]);
availHeight :
[Link] ([Link]);
52 | P a g e
colorDepth :
Returns the number of bits used to display one color.
[Link] ([Link]);
pixelDepth :
Returns the number of bits used for a single pixel.
[Link] ([Link]);
popup Windows Box
Alert:
Purpose: To display a simple message to the user.
Interaction: Shows a message with an "OK" button.
Returns: No return value (doesn't expect user input).
Prompt:
Purpose: To ask for user input.
Interaction: Shows a text box along with "OK" and "Cancel"
Returns: The input text if "OK" is clicked, null if "Cancel" is click.
Confirm:
Purpose: To ask for confirmation from the user (e.g., Yes/No,
OK/Cancel).
Interaction: Shows "OK" and "Cancel" buttons.
Returns: true if "OK" is clicked, false if "Cancel" is clicked.
BOM vs DOM
53 | P a g e