JavaScript एक important programming language है जिसका use websites को interactive बनाने, web applications develop करने, server-side programming और कई दूसरे development tasks में होता है।
अगर आप Frontend Developer, Full Stack Developer या React Developer बनना चाहते हैं, तो JavaScript की fundamentals समझना बहुत जरूरी है।
इस JavaScript Cheat Sheet में हम basic syntax से लेकर functions, arrays, objects, DOM manipulation, events, promises और modern JavaScript तक important concepts practical examples के साथ सीखेंगे।
JavaScript क्या है?#
JavaScript एक programming language है जिसका use applications में logic, interaction और dynamic behavior implement करने के लिए किया जाता है।
HTML webpage का structure define करता है, CSS उसका appearance control करता है और JavaScript functionality add करती है।
Example:
<button id="helloButton">Click Me</button>
<p id="message"></p>
<script>
document.getElementById("helloButton").addEventListener("click", function () {
document.getElementById("message").textContent = "Hello, JavaScript!";
});
</script>इस example में button click करने पर paragraph का text change हो जाता है।
JavaScript के common use cases:
- Interactive websites बनाना।
- Form validation करना।
- API से data fetch करना।
- Dynamic content display करना।
- React जैसे frontend frameworks use करना।
- Node.js के साथ backend applications बनाना।
JavaScript कैसे काम करता है?#
Browser में JavaScript engine code को execute करता है। Browser JavaScript को DOM जैसी Web APIs भी provide करता है, जिनकी मदद से code webpage के elements के साथ interact कर सकता है।
Basic workflow:
HTML → Page Structure
CSS → Page Styling
JavaScript → Logic & InteractionJavaScript सिर्फ browser तक limited नहीं है। Node.js जैसे runtime की मदद से इसे server-side applications में भी use किया जा सकता है।
याद रखें: JavaScript language है, जबकि browser और Node.js इसके अलग-अलग execution environments provide करते हैं।
JavaScript कैसे run करें?#
Method 1: Browser Console
- किसी webpage को browser में open करें।
- Developer Tools खोलें।
- Console tab select करें।
- JavaScript code लिखें और Enter दबाएँ।
Example:
console.log("Hello, World!");
console.log(10 + 20);Output:
Hello, World!
30Method 2: HTML File में JavaScript
एक index.html file बनाएं:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Practice</title>
</head>
<body>
<h2>JavaScript Practice</h2>
<script src="script.js"></script>
</body>
</html>अब उसी folder में script.js बनाएं:
console.log("JavaScript is running!");HTML file को browser में open करें और Console में output देखें।
Method 3: Node.js
Node.js installed होने पर script.js file को terminal से run कर सकते हैं:
node script.jsJavaScript Comments#
Comments code को explain करने के लिए लिखे जाते हैं। JavaScript इन्हें normal executable statements की तरह execute नहीं करती।
Single-line comment:
// Calculate the total price
const total = 100 + 50;Multi-line comment:
/*
This code calculates
the final amount.
*/
const total = 100 + 50;Comments का use logic समझाने के लिए करें, obvious code को बार-बार describe करने के लिए नहीं।
Variables: let, const और var#
Variables का use data store करने के लिए किया जाता है।
let age = 25;
const name = "Aman";
var city = "Chandigarh";| Keyword | Use | Reassignment |
|---|---|---|
let | Block-scoped variable | Allowed |
const | Block-scoped binding | Not allowed |
var | Function-scoped या global binding | Allowed |
Modern JavaScript में सामान्यतः const को prefer करें और जब variable को reassign करना हो, तब let use करें। var को समझना legacy code पढ़ने के लिए useful है।
let Example
let score = 10;
score = 20;
console.log(score); // 20const Example
const country = "India";
console.log(country);const binding को reassign नहीं कर सकते:
const score = 10;
score = 20; // TypeErrorलेकिन const object की properties change हो सकती हैं:
const user = {
name: "Aman",
};
user.name = "Rahul";
console.log(user.name); // Rahulconst object को immutable नहीं बनाता। यह सिर्फ variable binding को reassign होने से रोकता है।
JavaScript Data Types#
JavaScript में primitive values और objects होते हैं।
| Data Type | Example | Meaning |
|---|---|---|
| String | "Hello" | Text |
| Number | 100, 3.14 | Numbers |
| BigInt | 123n | बड़े integers |
| Boolean | true, false | True/false values |
| Undefined | undefined | Value assign नहीं हुई |
| Null | null | जानबूझकर empty value |
| Symbol | Symbol("id") | Unique primitive value |
| Object | { name: "Aman" } | Related data |
| Array | [10, 20, 30] | Ordered collection |
Example:
const name = "Aman";
const age = 25;
const isDeveloper = true;
const skills = ["HTML", "CSS", "JavaScript"];
const user = { name: "Aman", age: 25 };
const result = null;
console.log(typeof name); // string
console.log(typeof age); // number
console.log(typeof isDeveloper); // boolean
console.log(typeof user); // object
console.log(typeof result); // objectImportant: typeof null का result "object" आता है। यह JavaScript का historical behavior है।
Strings#
String का use text represent करने के लिए किया जाता है।
const firstName = "Aman";
const lastName = 'Sharma';
const message = `Hello, ${firstName}`;Template Literals
Backticks के अंदर ${} use करके variables या expressions insert कर सकते हैं।
const name = "Aman";
const age = 25;
console.log(`My name is ${name} and I am ${age} years old.`);Output:
My name is Aman and I am 25 years old.Important String Methods
const text = " JavaScript Cheat Sheet ";
console.log(text.length);
console.log(text.trim());
console.log(text.toUpperCase());
console.log(text.toLowerCase());
console.log(text.includes("JavaScript"));
console.log(text.slice(2, 12));
console.log(text.replace("Cheat Sheet", "Guide"));
console.log(text.split(" "));| Method / Property | Use |
|---|---|
.length | String length |
.trim() | Start/end whitespace remove करना |
.toUpperCase() | Uppercase text |
.toLowerCase() | Lowercase text |
.includes() | Text मौजूद है या नहीं |
.slice() | String का हिस्सा निकालना |
.replace() | Matching text replace करना |
.split() | String को array में divide करना |
Numbers और Mathematical Operations#
const a = 10;
const b = 3;
console.log(a + b); // 13
console.log(a - b); // 7
console.log(a * b); // 30
console.log(a / b); // 3.333...
console.log(a % b); // 1
console.log(a ** b); // 1000Useful Number Methods
console.log(Number("123")); // 123
console.log(Number.isNaN(NaN)); // true
console.log(Number.isInteger(10)); // true
console.log((12.345).toFixed(2)); // "12.35"
console.log(Math.round(4.6)); // 5
console.log(Math.floor(4.9)); // 4
console.log(Math.ceil(4.1)); // 5
console.log(Math.max(10, 20, 30)); // 30
console.log(Math.min(10, 20, 30)); // 10
console.log(Math.random()); // 0 से कम नहीं, 1 से कमtoFixed() string return करता है, number नहीं।
Type Conversion#
एक data type को दूसरे type में convert करना type conversion कहलाता है।
Explicit Conversion
const value = "100";
console.log(Number(value)); // 100
console.log(String(100)); // "100"
console.log(Boolean(1)); // trueImplicit Conversion
JavaScript कुछ operations में automatically type conversion कर सकती है।
console.log("5" + 2); // "52"
console.log("5" - 2); // 3
console.log(5 == "5"); // true
console.log(5 === "5"); // falseजहाँ possible हो, explicit conversion और strict equality use करें ताकि unexpected results से बच सकें।
Operators#
Operators values पर operations perform करते हैं।
Arithmetic Operators
const a = 10;
const b = 5;
console.log(a + b);
console.log(a - b);
console.log(a * b);
console.log(a / b);
console.log(a % b);
console.log(a ** b);Comparison Operators
console.log(10 > 5); // true
console.log(10 < 5); // false
console.log(10 >= 10); // true
console.log(10 <= 5); // false
console.log(10 === 10); // true
console.log(10 !== 5); // trueLogical Operators
const age = 25;
const hasID = true;
console.log(age >= 18 && hasID); // true
console.log(age < 18 || hasID); // true
console.log(!hasID); // false| Operator | Meaning |
|---|---|
&& | AND |
|| | OR |
! | NOT |
?? | Nullish coalescing |
?. | Optional chaining |
Nullish Coalescing (??)
जब value null या undefined हो, तब fallback value provide करने के लिए use होता है।
const username = null;
console.log(username ?? "Guest"); // Guest|| और ?? हमेशा interchangeable नहीं हैं:
console.log(0 || 10); // 10
console.log(0 ?? 10); // 0Conditions: if, else और switch#
Conditions का use decisions लेने के लिए किया जाता है।
if...else
const age = 20;
if (age >= 18) {
console.log("You can vote.");
} else {
console.log("You cannot vote yet.");
}else if
const marks = 75;
if (marks >= 90) {
console.log("Grade A");
} else if (marks >= 60) {
console.log("Grade B");
} else {
console.log("Keep practicing");
}Ternary Operator
Simple conditions को concise तरीके से लिखने के लिए:
const age = 20;
const status = age >= 18 ? "Adult" : "Minor";
console.log(status);Complex nested ternary expressions से बचें क्योंकि उन्हें पढ़ना मुश्किल हो सकता है।
switch
const day = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Unknown day");
}break missing होने पर execution अगले cases में continue कर सकता है।
Loops#
Loops का use किसी task को बार-बार execute करने के लिए किया जाता है।
for Loop
for (let i = 1; i <= 5; i++) {
console.log(i);
}while Loop
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}for...of
Iterable values, जैसे arrays के elements, पर iterate करने के लिए:
const fruits = ["Apple", "Banana", "Mango"];
for (const fruit of fruits) {
console.log(fruit);
}for...in
Object की enumerable property keys पर iterate करने के लिए:
const user = {
name: "Aman",
age: 25,
};
for (const key in user) {
console.log(key, user[key]);
}Array elements iterate करने के लिए सामान्यतः for...of या array methods अधिक suitable होते हैं।
break और continue
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue;
}
console.log(i);
}continue current iteration skip करता है। break loop को terminate करता है।
Functions#
Function reusable code block है जिसे जरूरत पड़ने पर call किया जा सकता है।
Function Declaration
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Aman"));Function Expression
const add = function (a, b) {
return a + b;
};
console.log(add(10, 20));Arrow Function
const multiply = (a, b) => {
return a * b;
};
console.log(multiply(4, 5));Single expression के लिए concise syntax:
const square = number => number * number;
console.log(square(5)); // 25Default Parameters
function greet(name = "Guest") {
return `Hello, ${name}`;
}
console.log(greet());
console.log(greet("Aman"));Rest Parameters
कई arguments को एक array में collect करने के लिए:
function sum(...numbers) {
return numbers.reduce((total, number) => total + number, 0);
}
console.log(sum(10, 20, 30)); // 60return क्यों जरूरी है?
function add(a, b) {
return a + b;
}
const result = add(10, 20);
console.log(result); // 30return के बिना function सामान्यतः undefined return करता है।
Scope: Global, Function और Block Scope#
Scope तय करता है कि variable कहाँ accessible है।
const globalName = "Aman";
function showName() {
const localName = "Rahul";
console.log(globalName);
console.log(localName);
}
showName();localName function के बाहर accessible नहीं है।
Block Scope
if (true) {
let message = "Hello";
const count = 10;
}
// console.log(message); // ReferenceErrorlet और const block-scoped होते हैं।
Best practice: Variables को उस छोटे scope में declare करें जहाँ उनकी जरूरत हो।
Arrays#
Array का use multiple values को ordered collection में store करने के लिए किया जाता है।
const fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]); // Apple
console.log(fruits[1]); // Banana
console.log(fruits.length); // 3JavaScript arrays zero-indexed होते हैं, यानी पहला element index 0 पर होता है।
Array में Items Add या Remove करना
const fruits = ["Apple", "Banana"];
fruits.push("Mango"); // End में add
fruits.pop(); // Last item remove
fruits.unshift("Orange"); // Start में add
fruits.shift(); // First item remove
console.log(fruits);Important Array Methods
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(number => number * 2);
const even = numbers.filter(number => number % 2 === 0);
const total = numbers.reduce((sum, number) => sum + number, 0);
const found = numbers.find(number => number > 3);
const exists = numbers.includes(3);
console.log(doubled); // [2, 4, 6, 8, 10]
console.log(even); // [2, 4]
console.log(total); // 15
console.log(found); // 4
console.log(exists); // true| Method | Use |
|---|---|
map() | हर element को transform करना |
filter() | Condition के आधार पर items चुनना |
reduce() | Values को एक result में combine करना |
find() | पहला matching element |
findIndex() | पहले matching element का index |
includes() | Value मौजूद है या नहीं |
some() | कम-से-कम एक element condition satisfy करता है |
every() | सभी elements condition satisfy करते हैं |
forEach() | हर element पर callback execute करना |
slice() | Array का हिस्सा निकालना; original array नहीं बदलता |
splice() | Array में items add/remove करना; original array बदलता है |
sort() | Array को sort करना; original array बदलता है |
map() और forEach() में Difference
map() नया array return करता है, जबकि forEach() सामान्यतः undefined return करता है।
const numbers = [1, 2, 3];
const result = numbers.map(number => number * 2);
console.log(result); // [2, 4, 6]const numbers = [1, 2, 3];
const result = numbers.forEach(number => {
console.log(number);
});
console.log(result); // undefinedObjects#
Object related data को key-value pairs में store करता है।
const user = {
name: "Aman",
age: 25,
city: "Chandigarh",
};
console.log(user.name);
console.log(user["city"]);Object Properties Update करना
const user = {
name: "Aman",
age: 25,
};
user.age = 26;
user.email = "aman@example.com";
console.log(user);Object Methods
const user = {
name: "Aman",
greet() {
return `Hello, ${this.name}`;
},
};
console.log(user.greet());यहाँ this.name उस object के name property को refer करता है जिसके context में method call हुआ है।
Arrow functions का अपना this नहीं होता। इसलिए object methods में this की जरूरत हो तो regular method syntax अक्सर बेहतर choice है।
Useful Object Methods
const user = {
name: "Aman",
age: 25,
};
console.log(Object.keys(user));
console.log(Object.values(user));
console.log(Object.entries(user));| Method | Result |
|---|---|
Object.keys() | Property keys का array |
Object.values() | Property values का array |
Object.entries() | Key-value pairs का array |
Object.hasOwn() | Object की own property check करना |
Example:
console.log(Object.hasOwn(user, "name")); // trueDestructuring#
Destructuring से arrays और objects की values को variables में conveniently extract कर सकते हैं।
Array Destructuring
const colors = ["Red", "Green", "Blue"];
const [first, second] = colors;
console.log(first); // Red
console.log(second); // GreenObject Destructuring
const user = {
name: "Aman",
age: 25,
};
const { name, age } = user;
console.log(name);
console.log(age);Renaming Properties
const user = {
name: "Aman",
};
const { name: userName } = user;
console.log(userName);Spread और Rest Operators#
Spread (...) iterable या object की properties को expand करने में मदद करता है।
Spread with Arrays
const first = [1, 2];
const second = [3, 4];
const combined = [...first, ...second];
console.log(combined); // [1, 2, 3, 4]Spread with Objects
const user = {
name: "Aman",
age: 25,
};
const updatedUser = {
...user,
age: 26,
};
console.log(updatedUser);यह shallow copy बनाता है। Nested objects automatically deep-copy नहीं होते।
Spread और Rest में Difference
- Spread: Values को expand करता है।
- Rest: कई values को एक array या parameter collection में collect करता है।
const numbers = [10, 20, 30];
console.log(...numbers); // 10 20 30function showItems(first, ...remaining) {
console.log(first);
console.log(remaining);
}
showItems("A", "B", "C");Optional Chaining (?.)#
Optional chaining nested property access करते समय null या undefined की वजह से होने वाले errors से बचने में मदद करती है।
const user = {
profile: {
name: "Aman",
},
};
console.log(user.profile?.name); // Aman
console.log(user.address?.city); // undefinedOptional chaining हर प्रकार के error को handle नहीं करती। यह विशेष रूप से nullish property access को short-circuit करती है।
DOM Manipulation#
DOM (Document Object Model) webpage के HTML elements को objects के रूप में represent करता है। Browser JavaScript को DOM access करने की APIs देता है।
Element Select करना
const title = document.getElementById("title");
const button = document.querySelector("button");
const items = document.querySelectorAll(".item");| Method | Use |
|---|---|
getElementById() | ID से element select करना |
querySelector() | CSS selector से पहला matching element |
querySelectorAll() | सभी matching elements का static NodeList |
Text Change करना
<h2 id="title">Old Title</h2>const title = document.getElementById("title");
title.textContent = "New Title";CSS Class Add या Remove करना
const box = document.querySelector(".box");
box.classList.add("active");
box.classList.remove("hidden");
box.classList.toggle("highlight");HTML Element Create करना
const paragraph = document.createElement("p");
paragraph.textContent = "New paragraph";
document.body.appendChild(paragraph);Security tip: Untrusted user input को innerHTML में directly insert न करें। Text display करने के लिए textContent safer default है।
Events#
Events browser में होने वाली activities हैं, जैसे button click, keyboard input या form submission।
Click Event
<button id="clickButton">Click Me</button>
<p id="output"></p>const button = document.getElementById("clickButton");
const output = document.getElementById("output");
button.addEventListener("click", () => {
output.textContent = "Button clicked!";
});Input Event
<input id="nameInput" placeholder="Enter your name">
<p id="greeting"></p>const input = document.getElementById("nameInput");
const greeting = document.getElementById("greeting");
input.addEventListener("input", () => {
greeting.textContent = `Hello, ${input.value}`;
});Form Submit Event
<form id="signupForm">
<input id="email" type="email" required>
<button type="submit">Submit</button>
</form>const form = document.getElementById("signupForm");
form.addEventListener("submit", event => {
event.preventDefault();
console.log("Form submitted");
});preventDefault() browser के default form submission behavior को रोकता है। Real applications में validation और server-side verification भी जरूरी हैं।
JSON#
JSON (JavaScript Object Notation) data exchange के लिए इस्तेमाल होने वाला text format है। APIs में JSON बहुत commonly use होता है।
const user = {
name: "Aman",
age: 25,
};Object को JSON String में Convert करना
const jsonString = JSON.stringify(user);
console.log(jsonString);Output:
{"name":"Aman","age":25}JSON String को Object में Convert करना
const jsonString = '{"name":"Aman","age":25}';
const data = JSON.parse(jsonString);
console.log(data.name); // AmanInvalid JSON parse करने पर error आ सकता है। Untrusted JSON parse करते समय error handling use करें।
JavaScript Modules: import और export#
Modules code को अलग-अलग files में organize करने में मदद करते हैं।
Export
math.js:
export function add(a, b) {
return a + b;
}
export const PI = 3.14159;Import
main.js:
import { add, PI } from "./math.js";
console.log(add(10, 20));
console.log(PI);Browser में modules use करते समय HTML में:
<script type="module" src="main.js"></script>use किया जा सकता है। Node.js में module setup project configuration पर depend कर सकता है।
Error Handling: try...catch#
Runtime errors को handle करने के लिए try...catch use कर सकते हैं।
try {
const data = JSON.parse("{invalid json}");
console.log(data);
} catch (error) {
console.error("Invalid JSON:", error.message);
}finally का use cleanup या ऐसे code के लिए होता है जिसे success या failure दोनों situations में चलना चाहिए।
try {
console.log("Processing...");
} catch (error) {
console.error(error);
} finally {
console.log("Finished");
}Errors को बिना समझे silently ignore न करें।
Synchronous और Asynchronous JavaScript#
Synchronous code सामान्यतः statements को क्रम से execute करता है।
console.log("First");
console.log("Second");
console.log("Third");Output:
First
Second
ThirdAsynchronous operations में किसी operation के complete होने का इंतजार करते हुए बाकी code को आगे चलने दिया जा सकता है।
Example:
console.log("Start");
setTimeout(() => {
console.log("Timer finished");
}, 1000);
console.log("End");Output:
Start
End
Timer finishedsetTimeout() callback को बाद के लिए schedule करता है। यह JavaScript के event loop और browser/host runtime के साथ काम करता है।
Promises#
Promise asynchronous operation के eventual success या failure को represent करता है।
Promise की तीन states:
pendingfulfilledrejected
Example:
const promise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("Operation successful");
} else {
reject(new Error("Operation failed"));
}
});
promise
.then(result => console.log(result))
.catch(error => console.error(error.message));| Method | Use |
|---|---|
.then() | Successful result handle करना |
.catch() | Rejection/error handle करना |
.finally() | Settlement के बाद cleanup करना |
async और await#
async/await Promise-based asynchronous code को readable तरीके से लिखने में मदद करता है।
function getUser() {
return Promise.resolve({
name: "Aman",
});
}
async function showUser() {
const user = await getUser();
console.log(user.name);
}
showUser();async function हमेशा Promise return करता है। await Promise settle होने तक उस async function के आगे के execution को suspend करता है; यह पूरी JavaScript thread को block नहीं करता। <Cite refs={[“turn318180search0″,”turn318180search4”]}/>
Error Handling with async/await
async function loadData() {
try {
const response = await fetch("/api/users");
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Unable to load data:", error.message);
}
}यहाँ response.ok check करना important है क्योंकि HTTP error status मिलने पर fetch() अपने आप Promise reject नहीं करता।
Fetch API#
fetch() का use network requests करने के लिए किया जाता है।
GET Request
async function getUsers() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const users = await response.json();
console.log(users);
} catch (error) {
console.error(error);
}
}
getUsers();POST Request
async function createUser() {
try {
const response = await fetch("https://example.com/api/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "Aman",
email: "aman@example.com",
}),
});
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const result = await response.json();
console.log(result);
} catch (error) {
console.error("Request failed:", error);
}
}यह example placeholder endpoint दिखाता है। इसे अपने actual API endpoint के अनुसार replace करें।
Classes#
JavaScript में class syntax objects बनाने और inheritance organize करने के लिए use हो सकता है।
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, ${this.name}`;
}
}
const user = new User("Aman", 25);
console.log(user.greet());Inheritance
class Admin extends User {
constructor(name, age, role) {
super(name, age);
this.role = role;
}
}
const admin = new Admin("Rahul", 30, "Admin");
console.log(admin.greet());
console.log(admin.role);JavaScript classes prototype-based inheritance के ऊपर एक convenient syntax provide करती हैं।
this Keyword#
this का value इस बात पर depend करता है कि function कैसे call किया गया है।
const user = {
name: "Aman",
greet() {
console.log(this.name);
},
};
user.greet(); // AmanRegular function में this का behavior call context पर depend करता है। Arrow function surrounding lexical scope से this लेता है।
इसीलिए arrow functions और regular functions को बिना सोचे एक-दूसरे के स्थान पर use नहीं करना चाहिए।
JavaScript Set और Map#
Set
Set unique values store करता है।
const numbers = new Set([1, 2, 2, 3, 3]);
console.log(numbers); // Set(3) {1, 2, 3}
numbers.add(4);
numbers.delete(1);
console.log(numbers.has(2)); // trueArray से duplicate values हटाने का example:
const values = [1, 2, 2, 3, 3];
const uniqueValues = [...new Set(values)];
console.log(uniqueValues); // [1, 2, 3]Map
Map key-value pairs store करता है। इसमें keys किसी भी type की हो सकती हैं।
const userRoles = new Map();
userRoles.set("Aman", "Admin");
userRoles.set("Rahul", "Editor");
console.log(userRoles.get("Aman")); // Admin
console.log(userRoles.has("Rahul")); // true
console.log(userRoles.size); // 2JavaScript Best Practices#
- By default
constuse करें; reassignment चाहिए तोletचुनें। varऔरlet/constके scope differences समझें।- Comparison में सामान्यतः
===और!==prefer करें। - Functions को छोटे और single-purpose रखें।
- Meaningful variable और function names रखें।
- Repeated code को reusable functions में organize करें।
- API calls में error handling और HTTP status checks रखें।
- User-provided data को blindly trusted न मानें।
- DOM में untrusted text display करने के लिए
textContentprefer करें। - Private keys, passwords और API secrets को frontend code में expose न करें।
- Arrays और objects को copy करते समय shallow-copy behavior समझें।
map()औरfilter()जैसे methods को उनके purpose के अनुसार use करें।- Modern syntax सीखें, लेकिन existing project के environment और tooling को ध्यान में रखें।
Common JavaScript Mistakes#
1. = और === को Confuse करना
const age = 20;
console.log(age === 20); // true= assignment के लिए है, जबकि === strict equality comparison के लिए है।
2. String और Number को Mix करना
console.log("10" + 5); // "105"
console.log(Number("10") + 5); // 153. const को Immutable समझना
const items = ["A", "B"];
items.push("C"); // Allowed
// items = ["X"]; // Error4. Array Method का Return Value भूलना
const numbers = [1, 2, 3];
const doubled = numbers.map(number => number * 2);
console.log(doubled);5. fetch() में HTTP Status Check न करना
const response = await fetch("/api/data");
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}Network error और HTTP error status अलग situations हैं। दोनों को सही तरीके से handle करें।
6. Missing DOM Element
const button = document.querySelector("#missingButton");
if (button) {
button.addEventListener("click", () => {
console.log("Clicked");
});
}अगर selector matching element नहीं ढूँढता, तो querySelector() null return करता है।
JavaScript Quick Reference#
| Task | Syntax |
|---|---|
| Variable declare करना | let count = 0; |
| Constant declare करना | const name = "Aman"; |
| Console output | console.log(value); |
| Function | function greet() {} |
| Arrow function | const add = (a, b) => a + b; |
| Condition | if (condition) {} |
| Loop | for (const item of items) {} |
| Array length | items.length |
| Array transform | items.map(callback) |
| Array filter | items.filter(callback) |
| Object property | user.name |
| Destructuring | const { name } = user; |
| Spread | const copy = [...items]; |
| DOM select | document.querySelector(".item") |
| Click event | element.addEventListener("click", callback) |
| JSON stringify | JSON.stringify(data) |
| JSON parse | JSON.parse(text) |
| Promise handler | promise.then().catch() |
| Async function | async function load() {} |
| Fetch API | await fetch(url) |
| Error handling | try { } catch (error) { } |
| Module import | import { add } from "./math.js"; |
| Module export | export function add() {} |
JavaScript Practice Exercises#
Beginner Exercises
- दो numbers को add करके result print करें।
- एक variable में age store करें और
if...elseसे adult/minor check करें। forloop से 1 से 10 तक numbers print करें।- एक function बनाएं जो दो numbers का product return करे।
- एक array में पाँच fruits रखें और उन्हें
for...ofसे print करें।
Intermediate Exercises
- Array में से केवल even numbers निकालने के लिए
filter()use करें। - Array के सभी numbers का sum
reduce()से calculate करें। - Object में name, email और city store करें और values print करें।
- Button click करने पर webpage का text change करें।
- एक JSON string को object में parse करें और उसकी properties display करें।
Advanced Exercises
async/awaitसे API data fetch करें और errors handle करें।- एक reusable function बनाएं जो array से duplicate values remove करे।
Userclass औरAdminsubclass बनाएं।- एक form बनाएं जिसमें input validation और submit event handling हो।
- दो JavaScript modules बनाएं और
import/exportसे उन्हें connect करें।
JavaScript Knowledge Check#
- JavaScript का मुख्य use क्या है?
let,constऔरvarमें क्या difference है?- Primitive data types कौन-कौन से हैं?
==और===में क्या अंतर है?map()औरforEach()का return behavior कैसे अलग है?- Object destructuring क्यों useful है?
- Spread और rest syntax में क्या difference है?
- DOM क्या है?
addEventListener()किसलिए use होता है?- Promise की तीन states क्या हैं?
asyncfunction क्या return करता है?fetch()response के साथresponse.okक्यों check करना चाहिए?- JavaScript modules में
importऔरexportका क्या role है? nullऔरundefinedमें क्या difference है?constobject की properties change क्यों हो सकती हैं?
Summary#
JavaScript modern web development की core programming languages में से एक है। इसकी fundamentals मजबूत होने से frontend development, React, Node.js और API integration सीखना आसान हो जाता है।
इस Cheat Sheet में आपने सीखा:
- JavaScript basics और execution
- Variables और data types
- Strings, numbers और operators
- Conditions और loops
- Functions और scope
- Arrays और objects
- Destructuring, spread और rest
- DOM manipulation और events
- JSON और modules
- Error handling
- Promises और
async/await - Fetch API
- Classes,
this, Set और Map - Best practices, common mistakes और quick reference
याद रखने वाली बात: JavaScript सीखने का सबसे अच्छा तरीका केवल syntax पढ़ना नहीं, बल्कि छोटे programs बनाना, उन्हें run करना और errors को खुद debug करना है।
आगे क्या सीखें?#
JavaScript fundamentals के बाद आपकी learning path में अगला topic है JSON।
JSON सीखते समय आप समझेंगे:
- JSON क्या है और JavaScript objects से कैसे अलग है।
- JSON syntax और data types।
JSON.stringify()औरJSON.parse()।- Nested objects और arrays।
- API responses में JSON का use।
- Common JSON errors और validation।
Suggested learning sequence:
- HTML
- CSS
- JavaScript
- JSON
- Fetch / REST APIs
- Node.js
- npm
- Build Tools (Vite)
- TypeScript
- React
आगे बढ़ने से पहले इस Cheat Sheet के beginner exercises खुद run करें। इससे JSON और API integration सीखने के लिए आपकी foundation मजबूत होगी।