0% found this document useful (0 votes)
24 views

Javascript

Javascript pdf book for beginner

Uploaded by

Danish Abdullah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Javascript

Javascript pdf book for beginner

Uploaded by

Danish Abdullah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Javascript

JavaScript Mein Basic Concepts:

1. Variables:
Asan Bhasha Mein: Variables ek tarah ke containers hote hain jisme hum values ko store karte hain.
Real Life Example: Imagine aapke paas ek dabba hai jisme aap apne toys ko rakh sakte hain. Yeh dabba wahi variable ki tarah hai.

Code:
let toyBox = 'Dabba jisme toys hain';

const vs let:
Asan Bhasha Mein: const ka istemal tab hota hai jab ek baar value assign ho gayi hai aur usko baad mein hum use change nahi
karenge. let ka istemal tab hota hai jab aapko value baar-baar change karni hai.
● Real Life Example: const ek sealed envelope ki tarah hai, jise ek baar bandh diya gaya toh baad mein kuch nahi badal sakta. let
ek diary ki tarah hai, jisme aap kuch bhi likh sakte hain aur badal sakte hain.
Code:
javascript
Copy code
const piValue = 3.14;
let itemCount = 10;

Strings ():
Asan Bhasha Mein: Strings mein hum text ko store karte hain, jaise ki "Hello" ya 'JavaScript'.
Real Life Example: Strings ek kitab ki pages ki tarah hote hain, jisme likha gaya text store hota hai.
Code:
javascript
Copy code
let greeting = "Hello, world!";

Concatenation (Jodna):
Asan Bhasha Mein: Strings ko jodne ke liye + ka istemal hota hai.
Real Life Example: Jaise hum words ko jodkar sentences banate hain, waise hi strings ko jodkar messages banate hain.
Code:
javascript
Copy code
let message = "Hello" + " " + "World!";

Comments ():
Asan Bhasha Mein: Comments code mein likhe jaate hain jisse dusre developers ko samajh aaye ki code kya kar raha hai.
Real Life Example: Jaise ek book mein author apni thoughts share karta hai, waise hi comments ke through developer apne thoughts
share karta hai.
Code:
javascript
Copy code
// Yeh ek comment hai, isme likha gaya code ko explain karta hai
let age = 25; // Is line mein humne age ko 25 assign kiya hai

Arrays ():
Asan Bhasha Mein: Arrays ek tarah ke list hote hain jisme hum multiple values store kar sakte hain.
Real Life Example: Ek basket jisme aap multiple fruits rakh sakte hain, waise hi array mein aap multiple values rakh sakte hain.
let fruits = ['Apple', 'Banana', 'Orange'];

Variable Kya Hai? What is Variable .

Variable ek container hai jisme ek value hoti hai, jaise ki hum kisi sum mein istemal karne ke liye ek number ka istemal kar sakte hain, ya
ek sentence ka hissa banane ke liye ek string ka istemal kar sakte hain.

Variable Ka Udaharan

Chaliye ek saral udaharan dekhte hain:

HTML
Play
Copy to Clipboard
<button id="button_A">Mujhe Dabayein</button>
<h3 id="heading_A"></h3>
JS
Play
Copy to Clipboard
const buttonA = document.querySelector("#button_A");
const headingA = document.querySelector("#heading_A");

buttonA.onclick = () => {
const name = prompt("Tumhara Naam Kya Hai?");
alert(`Hello ${name}, tumhe dekhkar achha laga!`);
headingA.textContent = `Swagat hai ${name}`;
};
Play

Is udaharan mein, jab button dabaya jata hai, toh kuch code chal jata hai. Pahli line screen par ek box dikhata hai jo padhne wale se
unka naam daalne ko kehta hai, aur fir woh value ek variable mein store ho jati hai. Dusri line ek welcome message dikhata hai jo unke
naam ko istemal karta hai, jise variable value se liya jata hai, aur teesri line uss naam ko page par dikhata hai.

Bina Variable Ke
Samajhne ke liye ki ye kyun faydemand hai, chaliye sochtein hain ki hum is udaharan ko bina variable istemal kiye kaise likhte hain. Ye
kuch is tarah dikhega:

HTML
Play
Copy to Clipboard
<button id="button_B">Mujhe Dabayein</button>
<h3 id="heading_B"></h3>
JS
Play
Copy to Clipboard
const buttonB = document.querySelector("#button_B");
const headingB = document.querySelector("#heading_B");

buttonB.onclick = () => {
alert(`Hello ${prompt("Tumhara Naam Kya Hai?")}, tumhe dekhkar achha laga!`);
headingB.textContent = `Swagat hai ${prompt("Tumhara Naam Kya Hai?")}`;
};
Play

Shayad aap is syntax ko abhi puri tarah se samajh nahi paaye honge, lekin aapko idea mil gaya hoga. Agar hame variables ka istemal
nahi hota, toh hume har bar jab naam ka istemal karna hota, padhne wale se puchhna padta!

Variables Ek Khaas Cheez Hai

Ek khaas baat variables mein yeh hai ki unme kuch bhi ho sakta hai — sirf strings aur numbers nahi. Variables mein complex data ya
phir puri functions bhi ho sakti hain jo kamaal ke kaam karne mein madad karti hain. Aap jaise hi JavaScript ke bare mein aur sikhte
jaayenge, aapko ye cheezein natural lagne lagegi.

Variable Banane Ka Tareeka

Variable ka istemaal karne ke liye, sabse pehle aapko usse banana padta hai — aur isse sahi taur par, hum ise declare karna kehte hain.
Iske liye, aapko let keyword likhna hai, uske baad aapko apne variable ka naam dena hai.

JS code

let meraNaam;
let meriUmra;
Yahan hum do variables bana rahe hain jinka naam meraNaam aur meriUmra hai. Aap apne
web browser ke console mein ye lines type karke dekhein. Uske baad, apne khud ke naam
chunne ke liye ek ya do variables banane ka prayas karein.

Initializing a variable

Variable Banane Ka Tareeka


Variable ko declare karne ke baad, aap usse ek value ke saath initialize kar sakte hain. Aapko iske liye variable ka naam likhna hoga,
uske baad ek equals sign (=) likhna hoga, aur fir value deni hogi.

myName = "Chris";
myAge = 37;
Ab console mein jaakar in lines ko type karein. Aapko confirm karne ke liye console
mein wapas aapne variable ko assigned ki gayi value dikhni chahiye, har case mein.
Fir, aap apne variable values ko console mein unke naam likhkar dekh sakte hain — in
lines ko try karein:
JS
Copy to Clipboard
myName;
myAge;
Aap ek hi samay mein variable declare aur initialize bhi kar sakte hain, is tarah se:
JS
Copy to Clipboard
let meraKutta = "Tiger";
Yeh shayad wahi hai jo aap aksar karenge, kyun ki yeh do karyo ko alag-alag lines
mein likhne se tej hota hai.
.
Var Ke Baare Mein Ek Note
Aapko shayad ek alag tarika bhi dikhai dega variables declare karne ka, var keyword ka istemal karke:
var meraNaam;
var meriUmra;
Jab JavaScript pehli baar banaya gaya tha, tab variables declare karne ka ye ekmatra tarika tha. var ka design confusing aur prone to
errors hai. Isliye, modern JavaScript ke versions mein let ko create kiya gaya tha, ek naya keyword variables banane ke liye jo var ke
comparison mein thoda alag kaam karta hai, uske issues ko fix karte hue.
Kuch simple differences neeche samjhayi gayi hain. Hum abhi sab differences pe nahi jaayenge, lekin jab aap JavaScript ke baare mein
aur sikhenge, aap inhe khud samajhenge (agar aap abhi inke baare mein padhna chahte hain toh, aap hamare let reference page ko
check kar sakte hain).
Var Ka Ek Noksan
Var ka ek important tareeka hai hoisting, jo var ke hoisting ke baare mein detail mein padhne ke liye hai.
Hoisting let ke saath kaam nahi karta. Agar hum upar diye gaye example mein var ki jagah let likhein toh, ye error ke saath fail ho
jayega. Ye ek achhi baat hai — variable ko initialize karne ke baad use declare karna confusing aur samajhne mein mushkil bana deta
hai.
Dusri baat, jab aap var ka istemal karte hain, aap ek hi variable ko jitni baar chahe declare kar sakte hain, lekin let ke saath aisa nahi
hota. Niche wala kaam karega:

var meraNaam = "Chris";


var meraNaam = "Bob";
Lekin ye dusri line par error dega:

let meraNaam = "Chris";


let meraNaam = "Bob";
Iske bajaye, aapko ye karna padega:

let meraNaam = "Chris";


meraNaam = "Bob";
Phir, isme sense hai ki aap let ka istemal karein, var ke bajaye. Modern browsers ne
2015 se let ko support kiya hai, isliye var ka istemal karne ki koi badi zarurat nahi
hai, agar aap explicitly ancient browsers ke liye code nahi likh rahe hain.
Note: Agar aap ye code apne browser ke console mein try kar rahe hain, toh please har
code block ko poora ek saath copy & paste karein. Chrome ke console mein ek feature
hai jisme variable re-declarations with let and const allowed hai
let meraNaam = "Chris";
let meraNaam = "Bob";
// Ek hi input: SyntaxError: Identifier 'meraNaam' has already been declared
let meraNaam = "Chris";
let meraNaam = "Bob";
// Do alag inputs: dono succeed karenge

Variable Ko Update Karna


Jab ek variable ko ek value ke saath initialize kar diya gaya hai, toh aap us value ko badal (ya update) sakte hain by use ek alag value
dena. Niche diye gaye lines ko console mein type karke dekhein:

meraNaam = "Bob";
meriUmra = 40;

Ek Note Variable Naming Rules Ke Baare Mein


Aap variable ko kuch bhi naam de sakte hain, lekin kuch seemayein hain. Aapko generally Latin characters (0-9, a-z, A-Z) aur
underscore character ka istemal karna chahiye.
Aapko dusre characters ka istemal nahi karna chahiye, kyun ki ye errors create kar sakte hain ya fir international audience ke liye
samajhna mushkil ho sakta hai.
Variable names ke shuruwat mein underscore ka istemal nahi karna chahiye — iska kuch specific meanings hota hai kuch JavaScript
constructs mein, isliye ye confusing ho sakta hai.
Variables ke shuruwat mein numbers ka istemal nahi karna chahiye. Ye allowed nahi hai aur isse error aayega.
Aap ek safe convention ko follow kar sakte hain, jise lower camel case kehte hain. Isme aap multiple words ko aapas mein jodte hain,
pehle word ko saara lower case mein rakhte hain, aur fir agli words ko capitalize karte hain. Humne article mein ab tak iska istemal kiya
hai.
Variable names ko intuitive banaye rakhein, taki vo data ko describe karein jo usmein store hai. Sirf single letters/numbers ya phir bahut
lambi phrases ka istemal na karein.
Variables case sensitive hote hain — toh myage aur myAge alag variables hain.
Ek aakhri point: Aapko JavaScript reserved words ka istemal apne variable names ke liye avoid karna padega — iska matlab hai vo
words jo actual JavaScript ke syntax ko form karte hain! Toh aap var, function, let, aur for jaise words ko variable names ke liye nahi
istemal kar sakte. Browsers inhe alag code items ke taur par recognize karte hain, aur aapko errors milenge.

Variable Naming Rules


- Variable ko aap kuch bhi naam de sakte hain, lekin isme kuch seemayein hain.
- Latin aksharon (0-9, a-z, A-Z) aur underscore ( _ ) ka istemal karein.
- Dusre aksharon ka istemal na karein, kyunki yeh antarraashtreey darbar ke liye kathin ho sakta hai.
- Variable ke naam ke shuruaat mein underscore ka istemal na karein, kyun ki yeh kuch JavaScript constructs mein specific hota hai aur
confuse kar sakta hai.
- Variable ke shuruaat mein sankhya ka istemal na karein, yeh error paida kar sakta hai.

Good Name Examples


- age
- myAge
- init
- initialColor
- finalOutputValue
- audio1
- audio2

Bad Name Examples


-1
-a
- _12
- myage
- MYAGE
- var
- Document
- skjfndskjfnbdskjfb
- thisisareallylongvariablenameman

Variable Types
- Numbers
- Strings
- Booleans िल
- Arrays
- Objectsऑब्जेक्ट्स
- Objectsऑब्जेक्ट्स
Dynamic Typing
- JavaScript ek "dynamically typed language" hai, iska matlab hai ki aapko variable mein kis prakar ka data type hoga specify karne ki
zarurat nahi hoti.

Constants in JavaScript

- Constants, variables ki tarah hote hain, lekin inhe declare karte waqt initialize karna zaruri hota hai.
- Inhe initialize karne ke baad aap inhe new value assign nahi kar sakte.
Numbers
- JavaScript mein hum numbers ka istemal karte hain. Jaise ki 5, 10, 3.14.

Operators:

Addition (+): Do numbers ko jodne ke liye `+` ka istemal hota hai, jaise `5 + 3`.

Subtraction (-): Ek number se doosre number ko minus karne ke liye `-` ka istemal
hota hai, jaise `8 - 2`.

Multiplication (*): Do numbers ko multiply karne ke liye `*` ka istemal hota hai,
jaise `4 * 6`.

Division (/):** Ek number ko doosre number se divide karne ke liye `/` ka istemal
hota hai, jaise `10 / 2`.

Modulus (%):Ek number ko doosre number se divide karne par bache hue remainder ko
nikalne ke liye `%` ka istemal hota hai, jaise `7 % 3`.
Example:
- Agar x = 5 aur y = 3 hai, toh x + y 8 dega, x - y 2 dega, x * y 15 dega, x / y
1.66 dega, aur x % y 2 dega
- In operators ko milake use karke hum math operations ko perform kar sakte hain
JavaScript mein.

JavaScript Mein Text (Strings)


Strings
JavaScript mein hum text ko strings kehte hain. Jaise ki `"Hello"`, JavaScript'`.

Concatenation
- Strings ko jodne ke liye `+` ka istemal hota hai. Jaise `"Hello" + "
String Methods
- JavaScript mein kai methods hote hain jo strings ke saath istemal hote hain. Jaise `length` method jo string ki length batata hai, jaise
`"Hello".length`.

Escape Characters - Kuch special characters ko use karne ke liye escape characters ka istemal hota hai, jaise `\"` (double quote inside
double quotes) ya `\'` (single quote inside single quotes).

Example:
Agar `name = "John"` hai, toh `"Hello, " + name` `"Hello, John"` dega.
Tip: - Strings ka istemal text ko store aur manipulate karne ke liye hota hai
JavaScript mein.
JavaScript Mein useful String Methods:

length
String ki length (kitne characters hain) batata hai.

let greeting = "Hello";


let length = greeting.length; // Returns 5

toUpperCase` / `toLowerCase`:
- String ko uppercase ya lowercase mein convert karta hai.

let text = "Hello";


let upperText = text.toUpperCase(); // Returns "HELLO"
let lowerText = text.toLowerCase(); // Returns "hello"
```

indexOf`:
- String mein specific substring ka first occurrence index batata hai.

let sentence = "JavaScript is powerful.";


let index = sentence.indexOf("is"); // Returns 11
```

substring` / `slice
- String se specific portion ko extract karta hai.

let message = "Hello World";


let part = message.substring(0, 5); // Returns "Hello"

replace`:
- Specific substring ko doosre substring se replace karta hai.
```javascript
let sentence = "JavaScript is fun.";
let newSentence = sentence.replace("fun", "awesome"); // Returns "JavaScript is
awesome."

String ke shuru aur ant mein extra spaces ko hata deta hai.

let text = " Hello ";


let trimmedText = text.trim(); // Returns "Hello"

Yeh kuch string methods hain JavaScript mein. Inka istemal karke hum strings ko asaanise manipulate kar sakte hain.

JavaScript Mein String Mein Substring Ki Presence Ko Test Karna:

includes: String mein kisi specific substring ki presence ko test karne ke liye includes method ka istemal hota hai.

let sentence = "JavaScript is amazing.";


let containsSubstring = sentence.includes("is"); // Returns true

indexOf: Agar aapko sirf substring ka index chahiye, toh indexOf ka istemal kar sakte hain.
let sentence = "JavaScript is amazing.";
let indexOfSubstring = sentence.indexOf("is"); // Returns 11 (index of "is")

Comparison Operator: Direct comparison operator === ka istemal bhi kiya ja sakta hai substring ki presence ko check karne ke liye.

let sentence = "JavaScript is amazing.";


let containsSubstring = sentence.indexOf("is") !== -1; // Returns true

Extracting a substring from a string


substring Method: substring method ka istemal kisi bhi string se specific portion ko extract karne ke liye hota hai.

let message = "Hello World";


let extractedSubstring = message.substring(0, 5); // Returns "Hello"
Yahan substring(0, 5) ne string ke 0th index se lekar 4th index tak ke characters ko extract kiya.
slice Method: slice method bhi substring extract karne ke liye upayogi hai.

let sentence = "JavaScript is powerful.";


let extractedSlice = sentence.slice(0, 10); // Returns "JavaScript"

Yahan slice(0, 10) ne string ke 0th index se lekar 9th index tak ke characters ko extract kiya.
Negative Index in slice. •Negative index ka istemal karke hum string ke ant se characters extract kar sakte hain.

let word = "JavaScript";


let lastThreeCharacters = word.slice(-3); // Returns "ipt"

substr Method: substr method specific index se lekar kuch characters ko extract karta hai.

let text = "Hello World";


let extractedSubstr = text.substr(6, 5); // Returns "World"
4 Yahan substr(6, 5) ne string ke 6th index se lekar 10th index tak ke characters ko extract kiya.

Arrays :
Arrays woh hai jaise ek magic ka dabba, jisme hum bahut saare items ko ek saath rakh sakte hain. Imagine kar, teri dukaan pe kuch
saaman hai, aur har ek ka daam alag-alag hai. Agar arrays na hote, toh tu ko har ek cheez ke liye alag-alag jagah pe jaake dekhna
padta, aur phir unka total nikalna bhi mushkil hota. Lekin arrays ke saath, sab kuch ek jagah sorted rehta hai, aur tu asani se har item ka
daam dekh sakta hai ya fir unka total nikal sakta hai.

Short Definition:
JavaScript mein arrays woh organized containers hain jo ek naam ke neeche multiple items ko store karte hain.
Example:

let productPrices = [10, 20, 15, 25, 30];


let firstPrice = productPrices[0]; // Kisi bhi ek item ko access karna
let totalPrices = 0;

for (let i = 0; i < productPrices.length; i++) {


totalPrices += productPrices[i]; // Array mein loop chalana
}

Varieties in JavaScript:
JavaScript mein kai tarah ke arrays hote hain jaise ki:
Numeric Arrays: Jo sirf numbers ko store karte hain.
String Arrays: Jo sirf strings ko store karte hain.
Mixed Arrays: Jo alag-alag types ke data ko store karte hain.
Multidimensional Arrays: Jo do ya do se zyada dimensions mein data ko store karte hain.

Yeh varieties JavaScript mein arrays ke use ka ek chhota sa snapshot hain.

JavaScript mein arrays ka real-life use kai jagah hota hai. Yahan kuch common scenarios hain:

Product Listings: E-commerce websites product details ko arrays mein store karte hain. Har product ek element hota hai, aur aap
easily unke saath interact kar sakte hain.

let products = [
{ name: 'Laptop', price: 800 },
{ name: 'Phone', price: 500 },
{ name: 'Headphones', price: 100 },
];

Student Grades: School management systems grades ko arrays mein store karte hain. Har student ka grade ek element hota hai.

let studentGrades = [90, 85, 92, 78, 95];


To-Do List:
To-Do list items ko arrays mein rakhna ek aam tareeka hai. Har to-do item ek element hota hai.

let toDoList = ['Study for exam', 'Buy groceries', 'Exercise'];


Dynamic Content on Websites: Website development mein, dynamic content ko arrays se manage karna common hai. For example,
carousel items, blog posts, or comments ko arrays mein store kiya ja sakta hai.

let blogPosts = [
{ title: 'Introduction to JavaScript', content: '...' },
{ title: 'Working with Arrays', content: '...' },
{ title: 'JavaScript Best Practices', content: '...' },
];

In examples se dikh raha hai ki arrays aapko data ko organize karne aur easily access karne mein madad karte hain real-life scenarios
mein.

Document Object Model (DOM) in JavaScript:

1. Introduction to DOM: DOM ek tree-like structure hai jo HTML ya XML document ko represent karta hai. JavaScript se iske
through, hum document ke elements ke saath interact kar sakte hain.

2. Accessing Elements: getElementById:

let heading = document.getElementById('main-heading');


getElementsByClassName:
let paragraphs = document.getElementsByClassName('paragraph');

3. Manipulating Elements:

Changing Content:

heading.textContent = 'New Heading';

Changing Styles:

heading.style.color = 'blue';

4. Creating Elements:

createElement:

let newParagraph = document.createElement('p');

Setting Content:

newParagraph.textContent = 'This is a new paragraph.';

5. Appending and Removing Elements:

Append to Body:

document.body.appendChild(newParagraph);

Remove Element:

document.body.removeChild(heading);

6. Event Handling:

Adding Event Listeners:

button.addEventListener('click', function() {
// Your code here
});

7. Traversal and Siblings:

Parent Element:

let parentElement = heading.parentElement;

Next Sibling:

let nextElement = heading.nextElementSibling;


8. Attributes:

Accessing Attributes:

let link = document.getElementById('my-link');


let hrefValue = link.getAttribute('href');

Setting Attributes:

link.setAttribute('target', '_blank');

9. Traversing the DOM:

Child Elements:

let children = parentElement.children;

First and Last Child:

let firstChild = parentElement.firstElementChild;


let lastChild = parentElement.lastElementChild;

10. Dynamic HTML:

innerHTML:

parentElement.innerHTML = '<p>This is new content.</p>';

Creating a List:

let list = ['Item 1', 'Item 2', 'Item 3'];


let listHTML = '<ul>';
list.forEach(item => {
listHTML += `<li>${item}</li>`;
});
listHTML += '</ul>';
parentElement.innerHTML = listHTML;

11. Forms and Input Handling:

Accessing Form Elements:

let form = document.getElementById('my-form');


let userInput = form.elements.username.value;

Form Submission:

form.addEventListener('submit', function(event) {
event.preventDefault(); // Prevents the default form submission
// Your form handling code here
});

12. Window Object:

Alerts and Prompts:

window.alert('This is an alert!');
let userResponse = window.prompt('Enter your name:');

Redirecting:

window.location.href = 'https://www.example.com';

JavaScript Mein Document Object Model (DOM) - Real-life Examples:

1. Interactive Form Handling:


Situation: Jab ek user form submit karta hai, aur aap chahte hain ki input ko validate karein aur page ko reload kiye bina ek
confirmation message dikhayein.

<form id="my-form">
<input type="text" id="username" required>
<button type="submit">Submit</button>
</form>
<div id="confirmation-message"></div>

// Form aur confirmation message ko access karein


let form = document.getElementById('my-form');
let confirmationMessage = document.getElementById('confirmation-message');

// Form submit event par kaam karein


form.addEventListener('submit', function(event) {
event.preventDefault(); // Page ko reload hone se rokna

// Username ko access karein


let username = form.elements.username.value;

// Username ka validation karein aur message update karein


if (username) {
confirmationMessage.textContent = `Hello, ${username}! Form submitted
successfully.`;
} else {
confirmationMessage.textContent = 'Please enter a username.';
}
});

2. Dynamic Content Update:


Situation: Jab aapke paas ek list of articles hai, aur aap chahte hain ki ek naye article ko add karne par webpage ko dynamically
update karein.
<ul id="article-list"></ul>
<button id="add-article">Add Article</button>

// Article list aur add article button ko access karein


let articleList = document.getElementById('article-list');
let addArticleButton = document.getElementById('add-article');

// Naya article add karne ka function


function addArticle() {
let newArticle = document.createElement('li');
newArticle.textContent = `New Article - ${new Date().toLocaleString()}`;
articleList.appendChild(newArticle);
}

// Add article button par click karne par addArticle function ko call karein
addArticleButton.addEventListener('click', addArticle);

3. Image Gallery with Modal:

Situation: Jab aap ek image gallery banate hain jisme ek image par click karne par woh fullscreen modal mein dikhai de

<div id="image-gallery">
<img src="image1.jpg" alt="Image 1" onclick="openModal('image1.jpg')">
<img src="image2.jpg" alt="Image 2" onclick="openModal('image2.jpg')">
<!-- More images... -->
</div>

<div id="modal">
<img id="modal-image">
<button onclick="closeModal()">Close</button>
</div>

// Image gallery aur modal ko access karein


let imageGallery = document.getElementById('image-gallery');
let modal = document.getElementById('modal');
let modalImage = document.getElementById('modal-image');

// Modal ko kholne ka function


function openModal(imageSrc) {
modal.style.display = 'block'; // Modal ko dikhayein
modalImage.src = imageSrc; // Image ko set karein
}

// Modal ko band karne ka function


function closeModal() {
modal.style.display = 'none'; // Modal ko hide kre
}

JavaScript Mein Event Handling - Samjhane Ka Tareeka:


Events Kya Hote Hain?
○ JavaScript mein events woh moments hote hain jab user kisi action ka response expect karta hai, jaise ki button click, form
submit, ya keyboard press.
○ Event Listeners Kya Hai?
○ Event listeners woh functions hote hain jo ek HTML element par specific event ko “sunte hain” aur jab woh event hota hai,
tab unka code execute hota hai.
○ Basic Syntax:
○ Kisi bhi element par event listener lagane ke liye, addEventListener ka istemal hota hai.

element.addEventListener('event_type', function() {
// Aapka code yahan hoga
});

Event Types:
○ Aam event types mein 'click', 'submit', 'mouseover', 'mouseout', 'keypress' shaamil hain.
○ Event Object:
○ Jab ek event hota hai, toh woh ek event object banata hai jismein event ke baare mein jaankari hoti hai, jaise ki kaunsa key
press hua, ya mouse ka kahan click hua.
○ Default Behavior Ko Rokna:
○ Kuch events ka default behavior hota hai, jaise ki form submit hone par page reload. Agar aap chahte hain ki yeh default
behavior na ho, toh event.preventDefault() ka istemal hota hai.
○ Multiple Event Listeners:
○ Aap ek hi element par multiple event listeners attach kar sakte hain, jaise ki click, hover, etc.

element.addEventListener('click', function() {
// Click event ka code
});

element.addEventListener('mouseover', function() {
// Mouseover event ka code
});
Bubbling and Capturing:
Events ek hierarchy mein propagate hote hain. Bubbling (upwards) aur capturing
(downwards) phases mein events travel karte hain. addEventListener ke third parameter
se aap decide kar sakte hain ki aap kis phase mein event ko catch karna chahte hain.
element.addEventListener('click', function() {
// Bubbling phase mein code
}, false); // Default is false for bubbling

element.addEventListener('click', function() {
// Capturing phase mein code
}, true);
Delegation:
● Event delegation mein, ek parent element par event listener lagaya jaata hai aur uske andar ke child elements ke events ko handle
kiya jaata hai. Yeh code maintainability ko badhata hai.

document.getElementById('parent-container').addEventListener('click', function(event)
{
if (event.target.tagName === 'LI') {
// Li element par click ka code
}
});

Asynchronous Nature of Events:


● Events in JavaScript are asynchronous, meaning they don’t block the execution of other code. Understanding this helps in
dealing with timing-related issues
element.addEventListener('click', function() {
setTimeout(function() {
// Code inside setTimeout executes asynchronously
}, 1000);
});
Event Handling Best Practices:
○ Maintain simplicity in event handling code.
○ Use event delegation for dynamic content.
○ Avoid inline event handlers for better separation of concerns.
○ Remove unnecessary event listeners to optimize performance.
○ Practical Example - Toggling Class on Click:
○ Ek element par click karke uski class toggle karna, jisse styling change ho.
<div id="toggle-element">Click me</div>

let toggleElement = document.getElementById('toggle-element');

toggleElement.addEventListener('click', function() {
this.classList.toggle('active'); // 'active' class ko toggle karein
});

AJAX aur API Fetch in JavaScript -


AJAX (Asynchronous JavaScript and XML):

Kya Hota Hai:


AJAX ek technique hai jiska istemal hum web pages ko dynamic banane ke liye karte hain, bina poora page reload kiye.
XMLHttpRequest Object:
Hum server se data fetch karne ke liye XMLHttpRequest object ka istemal karte hain.
javascript

let xhr = new XMLHttpRequest();

Server se Data Fetch Karna:


Example mein, hum server se data fetch kar rahe hain aur use console par print kar rahe hain.
javascript

xhr.open('GET', 'https://api.example.com/data', true);


xhr.onload = function() {
if (xhr.status === 200) {
let responseData = JSON.parse(xhr.responseText);
console.log(responseData);
}
};
xhr.send();

AJAX Request Steps:


● Request create karna (new XMLHttpRequest())
● Server ki taraf bhejna (xhr.open('GET', 'https://api.example.com/data', true);)
● Request ko send karna (xhr.send();)
● Response ka wait karna (xhr.onload = function() {...})

AJAX Request Example:
Ek simple GET request example.

let xhr = new XMLHttpRequest();


xhr.open('GET', 'https://api.example.com/data', true);

xhr.onload = function() {
if (xhr.status === 200) {
let responseData = JSON.parse(xhr.responseText);
console.log(responseData);
}
};

xhr.send();

Fetch API:
Modern browsers mein fetch API ka istemal hota hai, jo XMLHttpRequest ki tulna mein simpler syntax aur promises ka support karta
hai.

fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

Fetch API - POST Request Example:


POST request bhejne ka example.

fetch('https://api.example.com/postData', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ key1: 'value1', key2: 'value2' }),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

Fetch API:
Modern browsers mein fetch API ka istemal hota hai, jo XMLHttpRequest ki tulna mein simpler syntax aur promises ka support
karta hai.
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

Fetch API - POST Request Example:


POST request bhejne ka example.
fetch('https://api.example.com/postData', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ key1: 'value1', key2: 'value2' }),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

Async/Await with Fetch:


async aur await ka istemal karke fetch ko asaan banayein.
async function fetchData() {
try {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();

Handling API Responses:


API responses ko handle karne ke liye aap response status, headers, aur data ko dekh sakte hain.

fetch('https://api.example.com/data')
.then(response => {
console.log('Status Code:', response.status);
console.log('Headers:', response.headers);
return response.json();
})
.then(data => console.log('Data:', data))
.catch(error => console.error('Error:', error));

Promise-Based Fetch API:


Fetch API, XMLHttpRequest se modern hai aur Promises ka istemal karta hai, jo code ko
asaan banata hai.

fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

Headers and Authentication:


Aap request ke headers ko customize karke authentication tokens ya koi aur information server ko bhej sakte hain.

fetch('https://api.example.com/data', {
headers: {
'Authorization': 'Bearer your_access_token',
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

Timeouts:
Agar aap chahte hain ki request specific time ke andar complete ho jaaye, toh aap timeout ka istemal kar sakte hain.
let controller = new AbortController();
let signal = controller.signal;
setTimeout(() => controller.abort(), 5000); // Timeout set karein 5000 milliseconds
(5 seconds) ke liye
fetch('https://api.example.com/data', { signal })
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

Response Types:
Aap specify kar sakte hain ki aapko response kis type ka chahiye, jaise ki text, JSON, ya blob.

fetch('https://api.example.com/image', {
method: 'GET',
headers: {
'Content-Type': 'image/png',
},
})
.then(response => response.blob())
.then(imageBlob => {
let imageUrl = URL.createObjectURL(imageBlob);
console.log('Image URL:', imageUrl);
})
.catch(error => console.error('Error:', error));

Handling Multiple Concurrent Requests:


Agar aapko multiple requests ko concurrently handle karna hai, toh Promise.all ka istemal karein.

let request1 = fetch('https://api.example.com/data1');


let request2 = fetch('https://api.example.com/data2');
Promise.all([request1, request2])
.then(responses => Promise.all(responses.map(response => response.json())))
.then(dataArray => {
console.log('Data 1:', dataArray[0]);
console.log('Data 2:', dataArray[1]);
})
.catch(error => console.error('Error:', error));

Using Async/Await with Fetch:


async aur await ka istemal karke, aap fetch requests ko likh sakte hain ek synchronous tariko mein.

async function fetchData() {


try {
let response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
let data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
fetchData();

Fetch API:

Fetch Function:
Fetch API ek modern JavaScript API hai jo network requests ko bhejne aur data ko handle karne ke liye istemal hota hai.
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

Simple Fetch Example:


Fetch ka istemal server se data fetch karne ke liye hota hai. Yeh Promises ka istemal
karta hai.
fetch('https://api.example.com/data')
.then(response => response.json()) // Response ko JSON format mein parse karein
.then(data => console.log(data)) // Parse kiya gaya data ko console par print
karein
.catch(error => console.error('Error:', error)); // Error ko handle karein

POST Request with Fetch:


POST request bhejne ka example. Hum headers set karke aur data ko stringify karke bhej rahe hain.
fetch

Fetch API - API Fetching:

1. API Fetching - Introduction:

Simple Explanation: API Fetching ka istemal kisi bhi online service ya server se data lene ke liye hota hai.
Asan Bhasha Mein Samjhein: Yeh waisa hai jaise hum kisi online dictionary se meaning lete hain, waise hi hum API Fetching se kisi
server ya service se data lete hain.
Real Life Example: Maan lo aap ek weather app use kar rahe hain aur wahan se current temperature maloom karna chahte hain.

Code:
fetch('https://api.weather.com/current-temperature')
.then(response => response.json())
.then(data => console.log('Current Temperature:', data.temperature))
.catch(error => console.error('Error:', error));

2. API Fetching - Query Parameters:


Simple Explanation: Query Parameters ka istemal specific data ko filter karne ke liye hota hai.
Asan Bhasha Mein Samjhein: Jaise hum online shopping karte waqt “filter by price” ka option use karte hain, waise hi hum API Fetching
me Query Parameters ka istemal karte hain.
Real Life Example: Aap ek e-commerce app me hain aur specific price range ke products dekhna chahte hain.

•Code:

fetch('https://api.example.com/products?minPrice=50&maxPrice=100')
.then(response => response.json())
.then(data => console.log('Filtered Products:', data))
.catch(error => console.error('Error:', error));

Fetch API - API Fetching (Continued):

3. API Fetching - Authentication:

Simple Explanation: Authentication ka istemal data access ko secure banane ke liye hota hai.
Asan Bhasha Mein Samjhein: Jaise hum apne email account ko password se protect karte hain, waise hi API Fetching me Authentication
ka istemal hota hai.
Real Life Example: Aap ek social media app me hain aur apne account se related data access karna chahte hain.

Code:

const token = 'your_authentication_token';

fetch('https://api.example.com/user/profile', {
headers: {
'Authorization': `Bearer ${token}`, // Including authentication token in the
request headers
},
})
.then(response => response.json())
.then(data => console.log('User Profile:', data))
.catch(error => console.error('Error:', error));

4. API Fetching - Handling Errors:

Simple Explanation: Errors ka sahi taur par handle karna API Fetching me bahut zaroori hai.
Asan Bhasha Mein Samjhein: Jaise hum internet connection lost ho jaaye toh humara data nahi aata, waise hi API Fetching me bhi kuch
errors aati hain jo handle karni padti hain.
Real Life Example: Aap ek news app use kar rahe hain aur suddenly internet connection chala jata hai.

Code:

fetch('https://api.example.com/news')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log('News Data:', data))
.catch(error => console.error('Error:', error.message));

Api Fetching Intermediate concepts

Fetch API - Intermediate Concepts:

7. API Fetching - Caching Responses:


Simple Explanation: Caching ka istemal repeated API calls ko avoid karne ke liye hota hai.
•Asan Bhasha Mein Samjhein: Jaise hum kisi webpage ko refresh karte hain aur woh cache se load hoti hai, waise hi API Fetching me
Caching ka istemal hota hai.
Real Life Example: Aap ek weather app use kar rahe hain aur multiple baar same location ka weather check kar rahe hain.

Code:

// Using Cache API to store and retrieve responses


const cacheKey = 'weatherData';

// Checking if the response is already cached


caches.match(cacheKey).then(cachedResponse => {
if (cachedResponse) {
// If cached response exists, use it
return cachedResponse.json();
}
// If not cached, make a fresh API call and cache the response
return fetch('https://api.example.com/weather')
.then(response => response.json())
.then(data => {
caches.open(cacheKey).then(cache => cache.put(cacheKey, new
Response(JSON.stringify(data))));
return data;
});
})
.then(data => console.log('Weather Data:', data))
.catch(error => console.error('Error:', error));

8. API Fetching - Debouncing Requests:

Simple Explanation: Debouncing ka istemal rapid API requests ko control karne ke liye hota hai.
Asan Bhasha Mein Samjhein: Jaise hum ek search bar me continuously type karte hain aur results aate jaate hain, waise hi API Fetching
me Debouncing ka istemal hota hai.
Real Life Example: Aap ek search functionality implement kar rahe hain jahan continuously API requests ja rahi hain.

Code:

// Using debounce function to control rapid API requests


let debounceTimer;

function fetchData(searchQuery) {
// Clearing previous debounce timer
clearTimeout(debounceTimer);

// Setting new debounce timer to control rapid requests


debounceTimer = setTimeout(() => {
fetch(`https://api.example.com/search?q=${searchQuery}`)
.then(response => response.json())
.then(data => console.log('Search Results:', data))
.catch(error => console.error('Error:', error));
}, 300); // Adjust the debounce time as needed
}

// Assuming you have a search input field


const searchInput = document.getElementById('search');

// Adding event listener to trigger API requests on input change


searchInput.addEventListener('input', event => {
const searchQuery = event.target.value;
fetchData(searchQuery);
});

Fetch API - Intermediate Concepts (Continued):

9. API Fetching - Chaining Multiple Requests:

Simple Explanation: Multiple API requests ko chain karke execute karna.


Asan Bhasha Mein Samjhein: Ek API call ke baad dusri API call ko execute karna.
•Real Life Example: Aap ek e-commerce app me hain aur product details ke saath related reviews bhi retrieve karna chahte hain.

Code:

// Chaining multiple API requests


fetch('https://api.example.com/product-details')
.then(response => response.json())
.then(productDetails => {
console.log('Product Details:', productDetails);
// Using product details to make another API call for reviews
return fetch(`https://api.example.com/reviews?productId=$
{productDetails.productId}`);
})
.then(response => response.json())
.then(reviews => console.log('Product Reviews:', reviews))
.catch(error => console.error('Error:', error));

10. API Fetching - Customizing Headers:

Simple Explanation: Headers ka istemal request ko customize karne ke liye hota hai.
Asan Bhasha Mein Samjhein: Jaise hum kisi letter me sender ka address likhte hain, waise hi Headers se request ko customize karte
hain.
Real Life Example: Aap ek user-specific data retrieve kar rahe hain aur user authentication ke liye custom headers use kar rahe hain.

Code:

// Customizing headers for user authentication


const userId = 'user123';

fetch('https://api.example.com/user-data', {
headers: {
'Authorization': `Bearer ${userId}`, // Adding user ID in Authorization header
'X-Custom-Header': 'custom-value', // Adding a custom header
},
})
.then(response => response.json())
.then(userData => console.log('User Data:', userData))
.catch(error => console.error('Error:', error));

Fetch API - Intermediate Concepts (Continued):

9. API Fetching - Chaining Multiple Requests:

Simple Explanation: Ek ke baad ek API requests ko connect karke use karna.


Asan Bhasha Mein Samjhein: Imagine karain aap ek book store ke malik hain aur aap chahte hain ki jab koi book ki details dekhe, toh
uske saath related reviews bhi dikhaye jayein.
Real Life Example: Aap ek e-commerce app me hain aur product ki details ke baad reviews fetch karna chahte hain.

Code:

// Chaining multiple API requests


fetch('https://api.example.com/product-details')
.then(response => response.json())
.then(productDetails => {
console.log('Product Details:', productDetails);
// Using product details to make another API call for reviews
return fetch(`https://api.example.com/reviews?productId=$
{productDetails.productId}`);
})
.then(response => response.json())
.then(reviews => console.log('Product Reviews:', reviews))
.catch(error => console.error('Error:', error));

10. API Fetching - Customizing Headers:

Simple Explanation: Headers ka istemal request ko customize karne ke liye hota hai.
Asan Bhasha Mein Samjhein: Headers jaise ki ek letter mein hamare naam aur pata likhne ke liye use hota hai, waise hi Headers se
request ko customize karte hain.
Real Life Example: Aap ek specific user ke data ko retrieve kar rahe hain aur uske liye user authentication ke liye custom headers ka
istemal kar rahe hain.

Code:

// Customizing headers for user authentication


const userId = 'user123';

fetch('https://api.example.com/user-data', {
headers: {
'Authorization': `Bearer ${userId}`, // Adding user ID in Authorization header
'X-Custom-Header': 'custom-value', // Adding a custom header
},
})
.then(response => response.json())
.then(userData => console.log('User Data:', userData))
.catch(error => console.error('Error:', error));

Deep Explanation:

Chaining Multiple Requests:


First, an API call is made to fetch product details.
After receiving product details, a second API call is made to fetch reviews based on the product ID.
The results are then logged or used further.
Customizing Headers:
The ‘Authorization’ includes the user ID in a specific format for authentication.
The ‘X-Custom-Header’ is a custom header with a specific value, providing additional information or customization for the
request.

WhatsApp Example - Customizing Headers (Deep Explanation):

Scenario:
Jab aap WhatsApp par kisi ka online status dekhte hain, aap actually ek API request bhejte hain server ko. Yeh request
customize hoti hai taki server sahi response de sake.

Customizing Headers in WhatsApp:

1.User Authentication:
•Header Used: 'Authorization': 'Bearer <userToken>'
•Explanation: Aapka account ko verify karne ke liye aap apne request mein ek special token (Bearer token) include karte hain.
Yeh server ko batata hai ki aap ek valid user hain.
2.Custom Header for Online Status:
•Header Used: 'X-Request-Details': 'online-status'
•Explanation: Aap apne request mein ek aur custom header bhi include karte hain, jise ‘X-Request-Details’ kehte hain. Isme
‘online-status’ likha hota hai, yeh server ko batata hai ki aap specifically online status pooch rahe hain.

Example with Code:

// WhatsApp Online Status Check


const userToken = 'your_user_token';

fetch('https://whatsapp-api.com/online-status', {
headers: {
'Authorization': `Bearer ${userToken}`, // User authentication token
'X-Request-Details': 'online-status', // Custom header for online status
},
})
.then(response => response.json())
.then(onlineStatus => console.log('Online Status:', onlineStatus))
.catch(error => console.error('Error:', error));

Real-Life Analogy:
Imagine karain aap apne dost se puchte hain ki woh ghar par hain ya nahi. Aapke paas ek special card (Authorization) hota hai jo batata
hai ki aap dost hain, aur ek chitthi (Custom Header) hoti hai jisme likha hota hai ki aap specifically yeh puch rahe hain ki woh online hain
ya offline. Isi tarah se WhatsApp server ko bhi aapki request aati hai, jisme aap apna user authentication proof aur specific request likh
kar bhejte hain.

Asynchronous JavaScript - Introduction:

Scenario:
Imagine karo, aap ek online shopping website pe hain aur aap ek product ke reviews dekh rahe hain. Aapko reviews fetch karne mein
kuch time lagta hai, lekin aapko wait nahi karna padta. Isi tarah se, JavaScript mein bhi hum asynchronous programming ka istemal
karte hain jab kisi kaam mein thoda time lag sakta hai.

1. Promises - The Commitment:

Simple Explanation: Promise ek commitment hai ki kuch future mein hoga, ya toh successfully hoga ya phir error.
Asan Bhasha Mein Samjhein: Jaise aapke dost ne kaha ki woh aapke sath coffee peene aayenge, lekin woh abhi busy hain. Yeh ek
promise hai future activity ka.

2. async/await - The Waiter:

Simple Explanation: async/await ek tarika hai jisse aap wait kar sakte hain jab tak koi specific kaam complete nahi hota.
Asan Bhasha Mein Samjhein: Jaise aap restaurant mein hain aur waiter se keh rahe hain ki jab tak aapka order complete nahi hota, tab
tak main dessert nahi chahta.

Example with Code:

// Promises and async/await example


function fetchProductDetails(productId) {
return new Promise((resolve, reject) => {
// Simulating asynchronous task (fetching product details)
setTimeout(() => {
const productDetails = { id: productId, name: 'Example Product' };
resolve(productDetails);
}, 2000); // Simulating 2 seconds delay
});
}

async function displayProduct() {


try {
console.log('Fetching product details...');
const product = await fetchProductDetails(123);
console.log('Product details:', product);
} catch (error) {
console.error('Error fetching product details:', error);
}
}

// Calling the async function


displayProduct();

Real-Life Analogy:
Socho, aapne ek friend ko bulaya dinner pe, lekin woh thoda late ho gaya. Aapka wait karne ka commitment (Promise) hai. Ab
aap waiter se keh rahe hain ki jab tak mera friend nahi aata, tab tak dessert mat lao. Yeh aapka async/await ka analogy hai.

Is code mein fetchProductDetails function ek promise return karta hai jo simulate karta hai ki product details fetch ho rahe hain.
displayProduct function async hai, aur jab tak product details fetch nahi hote, woh wait karti hai.

Local storage introduction

Local Storage - Introduction:

Simple Explanation:
Local Storage ek web browser feature hai jisme data temporarily store hota hai. Yeh permanent nahi hota aur sirf specific website ke
liye accessible hota hai.

Asan Bhasha Mein Samjhein:


Samjho jaise aapne kisi online store mein shopping ki aur aapke cart mein kuch items hain. Agar aap site ko bandh karke baad mein
wapas aate hain, toh Local Storage se aapke cart ki details wapas mil jaati hain.

Real-Life Example:
Ek online store mein agar aapne login kiya hai, to Local Storage aapki login information ya preferences ko temporary storage mein
rakhega, taaki aapko dubara se login nahi karna padhe.

Code Example:

Local Storage ka basic use karte hain JavaScript mein:

// Data ko local storage mein store karna


localStorage.setItem('user', 'John Doe');

// Data ko local storage se retrieve karna


const storedUser = localStorage.getItem('user');
console.log('Stored User:', storedUser);

Real-Life Analogy:

Jaise aap kisi drawer mein apne important papers store karte hain, waise hi Local Storage website specific data ko temporary store
karta hai.

Local Storage - Use Case:

Simple Explanation:
Local Storage ka use karte hain jab humein chahiye ki website par kuch user-specific data temporary taur par store rahe, taki jab user
wapas aaye toh woh data available rahe.

Asan Bhasha Mein Samjhein:


Agar humein chahiye ki jab user site ko bandh karke dobara aaye, toh uski preferences ya kuch settings waisi hi rahe, toh hum Local
Storage ka istemal karte hain.

Real-Life Example:
Ek e-commerce website mein jab aap login karte hain aur kuch items apne cart mein daalte hain, toh yeh cart details Local Storage
mein temporarily store hoti hain. Aise mein, jab aap wapas aate hain, toh aapko apne cart mein wahi items dikhte hain.

Code Example:

Jab user login karta hai, user-specific data ko Local Storage mein store karna:

const user = {
id: 123,
name: 'John Doe',
preferences: ['dark mode', 'notifications'],
};

// User data ko Local Storage mein store karna


localStorage.setItem('user', JSON.stringify(user));

Real-Life Analogy:
Jaise aap apne office desk mein kuch notes ya preferences rakhte hain, waise hi Local Storage website ke liye temporary storage
provide karta hai.

Local Storage in JavaScript - Advanced Usage:

1. Data Types:

Local Storage mein data ko string format mein store kiya jata hai. Agar aap non-string data types store karte hain, toh use stringify aur
parse karna padta hai.

const userData = {
username: 'John',
age: 30,
};

// Storing object in Local Storage


localStorage.setItem('user', JSON.stringify(userData));

// Retrieving object from Local Storage


const storedUser = JSON.parse(localStorage.getItem('user'));
console.log('Stored User:', storedUser);

2. Handling Large Data:

Large amounts of data ko Local Storage mein store karne se behtar hota hai alternative storage options, jaise IndexedDB ka istemal
karna.

3. Expiry and Removal:

Local Storage mein data ko set karne ke saath ek optional parameter ke roop mein expiry time bhi set kiya ja sakta hai. Additionally,
removeItem function se specific item ko remove kiya ja sakta hai.

// Storing data with expiry time (5 minutes)


localStorage.setItem('token', 'xyz', new Date().getTime() + 5 * 60 * 1000);
// Removing specific item from Local Storage
localStorage.removeItem('token');

4. Events:

Local Storage mein koi bhi data update ya change hota hai toh uske liye storage event ka use kiya ja sakta hai.

window.addEventListener('storage', function(event) {
console.log('Storage Event:', event);
});

Real-Life Analogy:

Jaise aap apne refrigerator mein kuch items ko organize karte hain aur unhe expiry date ke hisaab se manage karte hain, waise hi Local
Storage mein bhi data ko organize aur manage kiya ja sakta hai.

IndexedDB in JavaScript - Introduction:

Simple Explanation:

IndexedDB ek client-side database hai jo browser mein available hota hai. Iska use large-scale data storage aur retrieval ke liye hota
hai.

Asan Bhasha Mein Samjhein:

IndexedDB ek aisa storage hai jisme hum large amounts of data ko organize aur access kar sakte hain, jisse Local Storage ki limitations
ko overcome kiya ja sake.

Real-Life Example:

Maan lo, aap ek offline note-taking app use kar rahe hain. IndexedDB se aap apne notes ko efficiently store aur retrieve kar sakte hain.

Code Example:

IndexedDB mein data store aur retrieve karna:

// Opening or creating a database


const request = indexedDB.open('MyDatabase', 1);

// Handling database open success


request.onsuccess = function(event) {
const db = event.target.result;
// Perform operations with the database
console.log('Database opened successfully:', db);
};

// Handling database open error


request.onerror = function(event) {
console.error('Error opening database:', event.target.error);
};
Real-Life Analogy:

Jaise aap apne documents aur files ko alag folders mein organize karte hain, waise hi IndexedDB mein hum apne data ko alag alag
object stores mein organize karte hain.

Web Storage vs IndexedDB:

Web Storage (LocalStorage aur SessionStorage) small amounts of data ke liye suitable hai, jabki IndexedDB large-scale data ke liye
better hai.
Web Storage synchronous hota hai, jabki IndexedDB asynchronous hota hai.
IndexedDB complex queries aur indexing support karta hai, jabki Web Storage sirf key-value pairs store karta hai.

Web Storage in JavaScript - Introduction:

Simple Explanation:
Web Storage ek simple key-value storage system hai jo client-side mein browser mein available hota hai.

Asan Bhasha Mein Samjhein:


Web Storage ka use karte hain jab hum small-sized data ko save aur retrieve karna chahte hain, jaise user preferences.

Real-Life Example:

Socho, aapne ek website pe login kiya aur woh website aapki preferences, jaise theme ya language, local storage mein save karti hai.

Code Example:

Local Storage mein data store aur retrieve karna:

// Storing data
localStorage.setItem('username', 'John');

// Retrieving data
const storedUsername = localStorage.getItem('username');
console.log('Stored Username:', storedUsername);

Real-Life Analogy:
Jaise aap apne wallet mein kuch important chhoti cheezein rakh kar carry karte hain, waise hi Web Storage mein hum kuch important
small-sized data ko rakh sakte hain.

Silly story generator ( Project)

Project Brief: Mazahiya Kahani Generator


Maqsad:
Is project ka maqsad mojooda HTML/CSS ko JavaScript ki madad se behtar banakar ek Mazahiya Kahani Generator banana hai. Is
program mein ek random mazahiya kahani generate honi chahiye, jisme naam ki custom tashkeel aur units ki tabdili ke liye user ki
darkhwast ka intezar ho.
Basic Setup:

main.js` naam ka ek naya file banao, jo aapki `index.html` file ke saath wahi folder mein hoga.
Apne HTML mein `<script>` element daalke `main.js` ko connect karo. Isko aapko HTML ke closing `</body>` tag se thoda pehle
daalna hai.

main.js File Banaye:


`main.js` naam ka ek naya file banaye, jise `index.html` ke directory ke saath mein rakhein.

JavaScript File Link Karein:


`index.html` mein closing `</body>` tag se thoda pehle, ek `<script>` element add karke JavaScript file ko link karein.

Initial Variables aur Functions

Variable aur Function Definitions Pura Karein:


Raw text file mein "1. COMPLETE VARIABLE AND FUNCTION DEFINITIONS" heading ke neeche wala code copy karein aur `main.js` ke
shuruwat mein paste karein.
Isse aapko variables milenge "Enter custom name" text field ke liye (`customName`), "Generate random story" button ke liye
(`randomize`), aur `<p>` element ke liye (`story`), jahan par story display hogi. Saath hi, ek function bhi hai
`randomValueFromArray()` jo array se random item lene ke liye hai.

Raw Text Strings:


- Raw text file mein "2. RAW TEXT STRINGS" section dekhein.
- Bada wala string `storyText` variable mein store karein.
- Teen sets ke strings ko arrays mein store karein, jo hain `insertX`, `insertY`, aur `insertZ`.

Event Listener aur Partial Function Definition

Event Listener aur Partial Function Definition:


Raw text file mein "3. EVENT LISTENER AND PARTIAL FUNCTION DEFINITION" heading ke neeche wala code copy karein aur `main.js`
ke ant mein paste karein.
Isse "Generate random story" button (`randomize`) par click hone par ek event listener aur ek partially-completed `result()` function
add hoti hai.

result() Function Ko complete kro

Humne ek naya variable `newStory` banaya hai, jiska initial value `storyText` ke barabar hai. Isse hum har button press par ek nayi
random story create kar sakte hain. Fir, teen naye variables - `xItem`, `yItem`, aur `zItem` banaye gaye hain, jo ki
`randomValueFromArray()` ko call karke `insertX`, `insertY`, aur `insertZ` se set kiye gaye hain, jisse har case mein result ek random
item ho.

Uske baad, humein `newStory` string mein teen placeholders - `:insertx:`, `:inserty:`, aur `:insertz:` ko replace karna hai, jisme humne
`xItem`, `yItem`, aur `zItem` ko integrate kiya hai. Iske liye humne `replaceAll()` method ka istemal kiya hai.

If block ke andar, `newStory` string mein jo 'Bob' naam hai, use `name` variable se replace kiya gaya hai. Yahaan hum keh rahe hain
"Agar `customName` text input mein koi value enter hui hai, toh story mein Bob ko us custom naam se replace karein."

Dusre if block ke andar, hum ye check kar rahe hain ki UK radio button select hua hai ya nahi. Agar hua hai, toh hum chahte hain ki story
mein weight aur temperature values ko pounds aur Fahrenheit se stones aur centigrade mein convert karein. Weight ko convert karne
ke liye 300 pounds ko stones mein convert karne ka formula istemal kiya gaya hai aur Fahrenheit ko centigrade mein convert karne ke
liye bhi ek formula ka istemal kiya gaya hai. Yeh dono values fir `newStory` string mein placeholders ke jagah replace ki gayi hain.

code

// HTML elements ka reference le lo


const customName = document.getElementById('customname'); // 'customname' id wale
input field ka reference
const randomize = document.querySelector('.randomize'); // '.randomize' class wale
button ka reference
const story = document.querySelector('.story'); // '.story' class wale paragraph ka
reference, jahan par story dikhayi jayegi

// Function jo ek array se random element choose kare


function randomValueFromArray(array) {
// Random index generate karo array ke length ke based on
const randomIndex = Math.floor(Math.random() * array.length);
// Aur fir waha se element return karo
return array[randomIndex];
}

// Main story ka template


const storyText = 'It was 94 fahrenheit outside, so :insertx: went for a walk. When
they got to :inserty:, they stared in horror for a few moments, then :insertz:. Bob
saw the whole thing, but was not surprised — :insertx: weighs 300 pounds, and it was
a hot day.';

// Arrays jisme placeholders ke liye possible values hain


const insertX = ['Willy the Goblin', 'Big Daddy', 'Father Christmas'];
const insertY = ['the soup kitchen', 'Disneyland', 'the White House'];
const insertZ = ['spontaneously combusted', 'melted into a puddle on the sidewalk',
'turned into a slug and crawled away'];

// Randomize button par click hone par ye function chalega


randomize.addEventListener('click', result);

// Result function jo story generate karega


function result() {
// Initial storyText ko newStory mein copy karo
let newStory = storyText;

// Random values choose karo placeholders ke liye


const xItem = randomValueFromArray(insertX);
const yItem = randomValueFromArray(insertY);
const zItem = randomValueFromArray(insertZ);

// Replace placeholders with randomly chosen values


newStory = newStory.replaceAll(':insertx:', xItem);
newStory = newStory.replaceAll(':inserty:', yItem);
newStory = newStory.replaceAll(':insertz:', zItem);

// If customName entered, replace 'Bob' with customName


if (customName.value !== '') {
const name = customName.value;
newStory = newStory.replaceAll('Bob', name);
}

// If UK radio button selected, convert weight and temperature units


if (document.getElementById("uk").checked) {
const weight = `${Math.round(300 * 0.0714286)} stone`;
const temperature = `${Math.round((94 - 32) * 5 / 9)} centigrade`;
newStory = newStory.replaceAll('94 fahrenheit', temperature);
newStory = newStory.replaceAll('300 pounds', weight);
}

// Set the content of the story paragraph to the new story


story.textContent = newStory;
// Make the story visible
story.style.visibility = 'visible';
}

codepen link - https://codepen.io/DanishAbdullahPy/pen/BabwQGM

Hoisting in Javascript

Hoisting ek JavaScript concept hai jisme variables aur functions ko code ke shuruat mein move kiya jata hai, lekin unki actual
initialization tab hoti hai jab code execute hota hai. Yani ki, aap ek variable ya function ko declare kar sakte hain baad mein bhi initialize
karke. Yeh code ki flow ko samajhne mein madad karta hai.
console.log(x); // Output: undefined

var x = 5;
console.log(x); // Output: 5
Yahan, `var x = 5;` likhne se pehle bhi console.log(x);` likha gaya hai, lekin
JavaScript hoisting ke karan, `x` pehle undefined (meaning not defined) dikha raha
hai. Phir `var x = 5;` se `x` ko 5 assign kiya gaya hai, aur dusre `console.log(x);`
mein `x` 5 ke equal dikha raha hai.

Iska matlab hai ki aap JavaScript mein variables ya functions ko declare karke initialize kar sakte hain, chahe aapne unhe code ke later
part mein define kiya ho. Hoisting ke karan, interpreter pehle sabhi declarations ko lekar aata hai.

Two types of Hoisting in Js


JavaScript mein do prakar ke hoisting hote hain: Variable Hoisting aur Function Hoisting.
1.Variable Hoisting:Variable hoisting ka matlab hai ki aap ek variable ko declare kar sakte hain aur use later mein initialize kar sakte
hain.

console.log(x); // Output: undefined


var x = 5;
console.log(x); // Output: 5
Yahan, `var x;` hoisting ke karan pehle ho gaya hai, phir `x` ko later mein
initialize kiya gaya hai.
2.Function Hoisting: Function hoisting mein aap ek function ko declare kar sakte hain
aur use code ke baad mein define kar sakte hain.
- Example:
sayHello(); // Output: Hello!

function sayHello() {
console.log("Hello!");
}
Yahan, `sayHello` function ko pehle hi call kiya ja raha hai, phir neeche define kiya gaya hai.
Hoisting code ki flow ko samajhne mein madad karta hai, lekin iska istemal dhyan se karna important hai taki code maintainable rahe.

Heap Memory :
Heap memory JavaScript mein dynamic memory allocation ke liye istemal hoti hai. Jab aap JavaScript mein kisi variable ko declare
karte hain, toh uska memory stack mein allocate hota hai. Lekin agar aap kisi object ya array ko declare karte hain, toh uska memory
heap mein allocate hota hai.

Heap memory ka use mainly dynamic data ke liye hota hai, jaise ki objects, arrays, ya functions. Isme data ko runtime par allocate kiya
jata hai, aur jab data ki zarurat khatam hojati hai, tab memory deallocate hojati hai.
Yeh approach JavaScript ko flexibility deta hai, lekin ek achhe memory management ki zarurat hoti hai taki unused memory ko free kiya
ja sake aur memory leaks na ho. Automatic Garbage Collection JavaScript mein is problem ko handle karta hai.

Another Type :

1. JavaScript Heap Memory: Heap memory mein dynamic data, jaise objects aur arrays, store hota hai. Stack memory basic data types
ke liye hota hai, lekin heap memory complex aur dynamic allocations ke liye.

2.Dynamic Memory Allocation:Heap memory. hume runtime me memory allocate aur deallocate karne ki permission deta hai. Yeh zaruri
hai jab hume data structures handle karna hai jinke size pehle se nahi pata hota.

3.Automatic Garbage Collection: JavaScript mein automatic garbage collection hota hai jo heap memory ko efficient taur par manage
karta hai.
Unused memory ko identify karke free karne se memory leaks se bachaya jata hai.

4. Memory Leaks:Memory leaks tab hoti hain jab memory allocate toh hoti hai lekin sahi se free nahi hoti. Object references ko sahi se
handle karke memory leaks ko avoid karna important hai.

5. Object Lifecycle: Heap memory mein objects ka lifecycle hota hai - create, use, aur phir dispose. Garbage collection unreferenced
objects ko identify karke memory free karta hai

7. Performance Considerations: Optimal performance ke liye efficient memory management zaruri hai. JavaScript memory handling ko
samajhna code likhne mein madad karta hai.

8. Asynchronous JavaScript Impact:


Asynchronous operations, jaise ki callbacks aur promises, bhi memory usage par impact daal sakte hain.

Types in Javascript
Primitive and Reference :
JavaScript mein primitive types mein strings, numbers, booleans, undefined, aur null hote hain. Ye types simple, immutable values ko
store karte hain. Reference types mein objects, arrays, aur functions hote hain, jo references ya addresses ko store karte hain, jisse
data ka memory location identify ho sake, aur inme changes kiye ja sakte hain.
Primitive types Example
// String (िस्ट्रंग)
let name = "John";
// Number (नंबर)
let age = 25;
// Boolean (बूिलयन)
let isStudent = true;
// Undefined (अिनधािर् रत)
let address;
// Null (नल)
let car = null;
Reference type example

// Object (ऑब्जेक्ट)
let person = { name: "John", age: 25 };

// Array (एरे)
// Array (एरे)
let numbers = [1, 2, 3];
// Function (फ़ंक्शन)
function add(a, b) {
return a + b;
}
Conditionals in JS

Basic If statement
let temperature = 25;

if (temperature > 30) {


console.log("It's a hot day!");
}
If else statement
let x = 10;

if (x > 0) {
console.log("x is positive");
} else if (x < 0) {
console.log("x is negative");
} else {
console.log("x is zero");
}
Is code mein, if, else if, aur else statements hain. Code x ki value par depend karta hai . Agar x positive hai, toh “x is positive” print
hoga. Agar x negative hai, toh “x is negative” print hoga Agar x zero hai, toh “x is zero” print hoga.

Else if statement

let time = 18;

if (time < 12) {


console.log("Good morning!");
} else if (time < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}

Nested if statement
Jab ek if statement ke andar doosri if statement hoti hai. Matlab, ek condition check karte hue, agar zarurat ho toh phir ek aur
condition check karte hain.
Isi ko nested if statement kehte hain

let isRaining = true;


let temperature = 15;

if (isRaining) {
if (temperature < 10) {
console.log("It's cold and raining.");
} else {
console.log("It's raining.");
}
} else {
console.log("It's not raining.");
}
Explanation:
Pehle check karo ke baarish ho rahi hai ya nahi (isRaining).
Agar haan, toh check karo thandak bhi hai ya nahi (temperature < 10).
Dono conditions true hain toh ek message print karo, nahi toh alag message print karo.
Agar baarish nahi ho rahi hai toh seedha ek aur message print karo.
Yeh tareeka istemal hota hai jab aapko ek hi branch mein aur conditions check karni hain.

Ternary operator
Ternary operator bhi ek shortcut hai if-else statements ke liye. Yeh ek hi line mein condition check karke value assign karta hai. Yahan
ek simple example hai:

let isSunny = true;


let mood = isSunny ? "Happy" : "Melancholy";
console.log("My mood is " + mood);
isRaining dekho, agar yeh true hai toh:
"Gloomy" ko mood variable mein daalo, nahi toh "Cheerful" ko daalo.
Iska matlab hai, agar baarish ho rahi hai toh mood gloomy hai, nahi toh cheerful hai. Aur yeh mood variable mein store ho jata hai.
Ternary operator ka istemal chhota aur clean code likhne ke liye hota hai.

Switch case statement


Switch statement ka istemal tab hota hai jab aapko ek variable ki multiple values ke liye alag-alag actions perform karne hain. Har value
ke liye aap alag case define karte hain, jismein specific code likha hota hai. Switch statement ka ek default case bhi hota hai, jo tab
chalta hai jab koi bhi case match nahi hota. Yeh code ko saaf, structured, aur easy to understand banata hai, especially jab aapko bahut
saare conditions handle karni ho.

let dayOfWeek = 3;
let dayName;

switch (dayOfWeek) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
// ... baaki ke cases
default:
dayName = "Invalid day";
}

console.log("Today is " + dayName);


dayOfWeek ki value dekho, agar 1 hai
toh
•dayName ko “Monday” bnega
•Aur switch se bahar nikalne k liye (break ka istemal hota hai).
Agar 2 hai toh dayName ko “Tuesday” banao. Aur switch se bahar niklo. Baaki ke din ke liye bhi aise hi.Agar koi bhi case match nahi hua
toh default wala block chalega, jismein dayName ko “Invalid day” bana diya jata hai.

Loops in javascript
For Loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
let i = 0`: Shuruaat mein i ko 0 se start hua - i < 5`: Jab tak i 5 se kam hai, tab tak chalta rhega - i++`: Har baar loop ke end mein i
badhega

While Loop
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Jab tak i 5 se kam hai, tab tak kaam karega Har baar loop ke end mein i badhta jaega !
Loops ka use hota hai jab koi kaam baar-baar karna ho. For loop mein pehle decide karte hain kitni baar karna hai, aur while loop mein
jab tak condition true hai, tab tak kaam hota rahega.

Function in JS
Function
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Bhai");
Yeh ek tarah ka tool hai jise hum banate hain, aur fir jab chahein, use karte hain. Yahan, `greet` naam ka function banaya gaya hai, jo
kisi bhii admi ka naam le lega aur usse ek greeting dega.
Parameter
Function ke andar `name` ek jagah hai jahan hum kisi ka naam daal sakte hain. Jaise yahan "Bhai" daala gaya hai.
Return Statement
function add(a, b) {
return a + b;
}

let result = add(3, 5);


console.log(result);
Yahan, `add` naam ka ek aur function hai, jo do numbers ko add karega. `return` ke zariye, yeh result ko hume wapas de dega. Jaise ki
yahan 3 aur 5 ko add karke result 8 aaya, jo fir humne print kiya.

Use of Functions
Functions ka use tab karte hain jab aapko ek specific task ko baar-baar karna ho, ya phir aap code ko modular banane chahte hain.
Yahan kuch scenarios hain jahan aap functions ka use kar sakte hain:
1.Reusability:Agar aapko ek particular kaam ko baar-baar karna hai, toh us kaam ko ek function mein define karke har baar function call
kar sakte hain, instead of har baar wahi code dubara likhna.

// Function to greet a user


function greetUser(name) {
console.log("Hello, " + name + "!");
}

// Reusing the function


greetUser("Alice");
greetUser("Bob");
greetUser("Charlie");

Yahan greetUser function hai jo user ko welcome karta hai. Is function ko alag-alag names ke sath call karke hum wahi welcome kaam
ko baar-baar kar rahe hain. Isse code clean aur re-usable ban jaata hai, kyunki welcome logic ek hi jagah define hui hai.
2. Modularity:Aap apne code ko small, manageable parts mein divide kar sakte hain. Har function ek specific kaam ko handle karega.

function fetchData(url) {
// Logic to fetch data from the given URL
return data;
}

function processData(data) {
// Logic to process the fetched data
return processedData;
}

let apiUrl = "https://example.com/data";


let fetchedData = fetchData(apiUrl);
let result = processData(fetchedData);

Explanation :

1. fetchData Function:

function fetchData(url) {
// Logic to fetch data from the given URL (simplified for example)
let data = "Fetched data from " + url;
return data;
}

•fetchData function ek URL se data fetch karta hai (example ke liye simplified
hai).
•let data = "Fetched data from " + url; mein hum URL ke sath ek chhota sa data
generate kar rahe hain, jaise ki “Fetched data from https://example.com/data”.
•return data; se yeh fetched data ko wapas bhejta hai.

2. processData Function:

function processData(data) {
// Logic to process the fetched data (simplified for example)
let processedData = "Processed: " + data;
return processedData;
}

•processData function fetched data ko process karta hai (example ke liye


simplified hai).
•let processedData = "Processed: " + data; mein humein woh fetched data milta hai,
jise hum process karte hain. Yahan ek chhota sa processing kiya gaya hai, jaise ki
“Processed: Fetched data from https://example.com/data”.
•return processedData; se yeh processed data ko wapas bhejta hai.

3. Using the Functions:

let apiUrl = "https://example.com/data";


let fetchedData = fetchData(apiUrl);
let result = processData(fetchedData);

•let apiUrl = "https://example.com/data"; mein humne ek example URL rakha hai.


•let fetchedData = fetchData(apiUrl); se fetchData function ko call kiya gaya aur
URL ke sath data fetch kiya gaya, jo fetchedData mein store hua.
•let result = processData(fetchedData); se processData function ko call kiya gaya,
jismein fetchedData ko process kiya gaya, aur result result variable mein store hua.

4. Printing the Result:

console.log(result);

•console.log(result); se humne processed result ko console par print kiya.

Toh, is example mein fetchData function se data fetch kiya gaya aur processData
function se woh data process kiya gaya, jiska result console par print hua

3. Readability:Functions aapke code ko padhne mein aur samajhne mein madad karte hain, kyunki aap ek function ka naam dekhkar
samajh sakte hain ki woh kya kaam karta hai.

function displayMessage(message) {
// Logic to display a message
console.log(message);
}

displayMessage("Hello, World!");

4. Parameterisation: Aap functions ke madhyam se parameters pass karke dynamic behavior achieve kar sakte hain. Isse aap ek hi
function ko alag-alag values ke sath use kar sakte hain.
function greet(name) {
console.log("Hello, " + name + "!");
}

greet("Alice");
greet("Bob");
Yeh hain kuch common situations jahan aap functions ka istemal kar sakte hain. Har function ek specific task ko perform karta hai, aur
isse aapka code organized aur maintainable rehta hai.

Parameters
Parameters function ke definition mein hote hain. Yeh variables hote hain jo function ke through receive kiya jaata hai
Example:
function greet(name) {
console.log("Hello, " + name + "!");
}
Yahan, `name` ek parameter hai.

Arguments

Arguments function ko call karte waqt diye jaate hain. Yeh values hote hain jo function ke parameters ko receive karta hai
greet("Bhai");
Yahan, "Bhai" ek argument hai jo `greet` function ko diya gaya hai. Is argument ki value `name` parameter mein jaayegi. Toh,
parameter function ke definition mein hota hai aur argument function ko call karte waqt diya jata hai.

Arrays
Array ek tarah ka box hai jisme aap multiple items store kar sakte hain, jaise ki fruits ka box. ( An array is a data structure that stores
multiple items in a single variable.)
Method to Make Array

let fruits = ["Apple", "Banana", "Orange", "Mango"];


Array ke Elements ( Array Elements:

Elements in an array are accessed using indices, starting from 0.


console.log(fruits[0]); // Output: Apple)
Elements ko access karne ke liye hum array ke index ka istemal karte hain, jisme pehla element 0 se shuru hota hai.
console.log(fruits[0]); // Output: Apple

Length of Arrays
(Array Length: The length property indicates how many elements are in the array.)
length property se aap janenge ki kitne elements hain is array me
console.log(fruits.length); // Output: 4

Arrays Method:

1. Push -Naya element add karna.


( Add a new element)
fruits.push("Grapes");
// Array now: ["Apple", "Banana", "Orange", "Mango", "Grapes"]

2. Pop - Last element hataya jata hai


(Remove the last element)
fruits.pop();
// Array now: ["Apple", "Banana", "Orange", "Mango"]

3. Shift -Pehla element hataya jata hai Isme


(Removes the first element)
fruits.shift();
// Array now: ["Banana", "Orange", "Mango"]

4. Unshift - Pehle mein naya element add karne ko kehte hain.


(Add a new element in the beginning)
fruits.unshift("Pineapple");
// Array now: ["Pineapple", "Banana", "Orange", "Mango"]

5. Slice
(Extract specific elements into a new array.)
let slicedFruits = fruits.slice(1, 3);
// slicedFruits: ["Banana", "Orange"]

6. IndexOf- Element ka index pata krta hai


(Find the index of an element.)
let index = fruits.indexOf("Orange");
// index: 2
7. Includes - Element array mein hai ya nahi, yeh check karne ko kehte hain
(Check if an element is present in the array.)
let hasBanana = fruits.includes("Banana");
// hasBanana: true

8. Join : Elements ko ek string mein convert karna.


(Convert elements into a string.)
let joinedString = fruits.join(", ");
// joinedString: "Banana, Orange, Mango"

You might also like