Javascript
Javascript
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 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
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!
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 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
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:
meraNaam = "Bob";
meriUmra = 40;
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.
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.
toUpperCase` / `toLowerCase`:
- String ko uppercase ya lowercase mein convert karta hai.
indexOf`:
- String mein specific substring ka first occurrence index batata hai.
substring` / `slice
- String se specific portion ko extract karta hai.
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.
Yeh kuch string methods hain JavaScript mein. Inka istemal karke hum strings ko asaanise manipulate kar sakte hain.
includes: String mein kisi specific substring ki presence ko test karne ke liye includes method ka istemal hota hai.
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.
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.
substr Method: substr method specific index se lekar kuch characters ko extract karta hai.
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:
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.
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 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.
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.
3. Manipulating Elements:
Changing Content:
Changing Styles:
heading.style.color = 'blue';
4. Creating Elements:
createElement:
Setting Content:
Append to Body:
document.body.appendChild(newParagraph);
Remove Element:
document.body.removeChild(heading);
6. Event Handling:
button.addEventListener('click', function() {
// Your code here
});
Parent Element:
Next Sibling:
Accessing Attributes:
Setting Attributes:
link.setAttribute('target', '_blank');
Child Elements:
innerHTML:
Creating a List:
Form Submission:
form.addEventListener('submit', function(event) {
event.preventDefault(); // Prevents the default form submission
// Your form handling code here
});
window.alert('This is an alert!');
let userResponse = window.prompt('Enter your name:');
Redirecting:
window.location.href = 'https://www.example.com';
<form id="my-form">
<input type="text" id="username" required>
<button type="submit">Submit</button>
</form>
<div id="confirmation-message"></div>
// Add article button par click karne par addArticle function ko call karein
addArticleButton.addEventListener('click', addArticle);
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>
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
}
});
toggleElement.addEventListener('click', function() {
this.classList.toggle('active'); // 'active' class ko toggle karein
});
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('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('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));
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));
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));
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 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));
•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));
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:
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));
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));
Code:
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:
function fetchData(searchQuery) {
// Clearing previous debounce timer
clearTimeout(debounceTimer);
Code:
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:
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));
Code:
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:
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:
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.
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.
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.
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.
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.
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.
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.
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.
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:
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.
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.
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'],
};
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.
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,
};
Large amounts of data ko Local Storage mein store karne se behtar hota hai alternative storage options, jaise IndexedDB ka istemal
karna.
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.
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.
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.
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:
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 (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.
Simple Explanation:
Web Storage ek simple key-value storage system hai jo client-side mein browser mein available hota hai.
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:
// 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.
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.
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
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.
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.
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 (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
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
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 dayOfWeek = 3;
let dayName;
switch (dayOfWeek) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
// ... baaki ke cases
default:
dayName = "Invalid day";
}
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;
}
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.
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;
}
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;
}
console.log(result);
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
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:
5. Slice
(Extract specific elements into a new array.)
let slicedFruits = fruits.slice(1, 3);
// slicedFruits: ["Banana", "Orange"]