Skip to content

JavaScript Cheat Sheet: Syntax, Examples & JS Concepts in Hindi

Updated 13 Oct 2026 8 min scan

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:

Code
<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:

Code
HTML → Page Structure
CSS → Page Styling
JavaScript → Logic & Interaction

JavaScript सिर्फ browser तक limited नहीं है। Node.js जैसे runtime की मदद से इसे server-side applications में भी use किया जा सकता है।

याद रखें: JavaScript language है, जबकि browser और Node.js इसके अलग-अलग execution environments provide करते हैं।

JavaScript कैसे run करें?#

Method 1: Browser Console

  1. किसी webpage को browser में open करें।
  2. Developer Tools खोलें।
  3. Console tab select करें।
  4. JavaScript code लिखें और Enter दबाएँ।

Example:

Code
console.log("Hello, World!");
console.log(10 + 20);

Output:

Code
Hello, World!
30

Method 2: HTML File में JavaScript

एक index.html file बनाएं:

Code
<!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 बनाएं:

Code
console.log("JavaScript is running!");

HTML file को browser में open करें और Console में output देखें।

Method 3: Node.js

Node.js installed होने पर script.js file को terminal से run कर सकते हैं:

Code
node script.js

JavaScript Comments#

Comments code को explain करने के लिए लिखे जाते हैं। JavaScript इन्हें normal executable statements की तरह execute नहीं करती।

Single-line comment:

Code
// Calculate the total price
const total = 100 + 50;

Multi-line comment:

Code
/*
This code calculates
the final amount.
*/
const total = 100 + 50;

Comments का use logic समझाने के लिए करें, obvious code को बार-बार describe करने के लिए नहीं।

Variables: let, const और var#

Variables का use data store करने के लिए किया जाता है।

Code
let age = 25;
const name = "Aman";
var city = "Chandigarh";
KeywordUseReassignment
letBlock-scoped variableAllowed
constBlock-scoped bindingNot allowed
varFunction-scoped या global bindingAllowed

Modern JavaScript में सामान्यतः const को prefer करें और जब variable को reassign करना हो, तब let use करें। var को समझना legacy code पढ़ने के लिए useful है।

let Example

Code
let score = 10;
score = 20;

console.log(score); // 20

const Example

Code
const country = "India";

console.log(country);

const binding को reassign नहीं कर सकते:

Code
const score = 10;
score = 20; // TypeError

लेकिन const object की properties change हो सकती हैं:

Code
const user = {
  name: "Aman",
};

user.name = "Rahul";

console.log(user.name); // Rahul

const object को immutable नहीं बनाता। यह सिर्फ variable binding को reassign होने से रोकता है।

JavaScript Data Types#

JavaScript में primitive values और objects होते हैं।

Data TypeExampleMeaning
String"Hello"Text
Number100, 3.14Numbers
BigInt123nबड़े integers
Booleantrue, falseTrue/false values
UndefinedundefinedValue assign नहीं हुई
Nullnullजानबूझकर empty value
SymbolSymbol("id")Unique primitive value
Object{ name: "Aman" }Related data
Array[10, 20, 30]Ordered collection

Example:

Code
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); // object

Important: typeof null का result "object" आता है। यह JavaScript का historical behavior है।

Strings#

String का use text represent करने के लिए किया जाता है।

Code
const firstName = "Aman";
const lastName = 'Sharma';
const message = `Hello, ${firstName}`;

Template Literals

Backticks के अंदर ${} use करके variables या expressions insert कर सकते हैं।

Code
const name = "Aman";
const age = 25;

console.log(`My name is ${name} and I am ${age} years old.`);

Output:

Code
My name is Aman and I am 25 years old.

Important String Methods

Code
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 / PropertyUse
.lengthString 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#

Code
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); // 1000

Useful Number Methods

Code
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

Code
const value = "100";

console.log(Number(value)); // 100
console.log(String(100)); // "100"
console.log(Boolean(1)); // true

Implicit Conversion

JavaScript कुछ operations में automatically type conversion कर सकती है।

Code
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

Code
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

Code
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); // true

Logical Operators

Code
const age = 25;
const hasID = true;

console.log(age >= 18 && hasID); // true
console.log(age < 18 || hasID); // true
console.log(!hasID); // false
OperatorMeaning
&&AND
||OR
!NOT
??Nullish coalescing
?.Optional chaining

Nullish Coalescing (??)

जब value null या undefined हो, तब fallback value provide करने के लिए use होता है।

Code
const username = null;

console.log(username ?? "Guest"); // Guest

|| और ?? हमेशा interchangeable नहीं हैं:

Code
console.log(0 || 10); // 10
console.log(0 ?? 10); // 0

Conditions: if, else और switch#

Conditions का use decisions लेने के लिए किया जाता है।

if...else

Code
const age = 20;

if (age >= 18) {
  console.log("You can vote.");
} else {
  console.log("You cannot vote yet.");
}

else if

Code
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 तरीके से लिखने के लिए:

Code
const age = 20;

const status = age >= 18 ? "Adult" : "Minor";

console.log(status);

Complex nested ternary expressions से बचें क्योंकि उन्हें पढ़ना मुश्किल हो सकता है।

switch

Code
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

Code
for (let i = 1; i <= 5; i++) {
  console.log(i);
}

while Loop

Code
let i = 1;

while (i <= 5) {
  console.log(i);
  i++;
}

for...of

Iterable values, जैसे arrays के elements, पर iterate करने के लिए:

Code
const fruits = ["Apple", "Banana", "Mango"];

for (const fruit of fruits) {
  console.log(fruit);
}

for...in

Object की enumerable property keys पर iterate करने के लिए:

Code
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

Code
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

Code
function greet(name) {
  return `Hello, ${name}!`;
}

console.log(greet("Aman"));

Function Expression

Code
const add = function (a, b) {
  return a + b;
};

console.log(add(10, 20));

Arrow Function

Code
const multiply = (a, b) => {
  return a * b;
};

console.log(multiply(4, 5));

Single expression के लिए concise syntax:

Code
const square = number => number * number;

console.log(square(5)); // 25

Default Parameters

Code
function greet(name = "Guest") {
  return `Hello, ${name}`;
}

console.log(greet());
console.log(greet("Aman"));

Rest Parameters

कई arguments को एक array में collect करने के लिए:

Code
function sum(...numbers) {
  return numbers.reduce((total, number) => total + number, 0);
}

console.log(sum(10, 20, 30)); // 60

return क्यों जरूरी है?

Code
function add(a, b) {
  return a + b;
}

const result = add(10, 20);
console.log(result); // 30

return के बिना function सामान्यतः undefined return करता है।

Scope: Global, Function और Block Scope#

Scope तय करता है कि variable कहाँ accessible है।

Code
const globalName = "Aman";

function showName() {
  const localName = "Rahul";
  console.log(globalName);
  console.log(localName);
}

showName();

localName function के बाहर accessible नहीं है।

Block Scope

Code
if (true) {
  let message = "Hello";
  const count = 10;
}

// console.log(message); // ReferenceError

let और const block-scoped होते हैं।

Best practice: Variables को उस छोटे scope में declare करें जहाँ उनकी जरूरत हो।

Arrays#

Array का use multiple values को ordered collection में store करने के लिए किया जाता है।

Code
const fruits = ["Apple", "Banana", "Mango"];

console.log(fruits[0]); // Apple
console.log(fruits[1]); // Banana
console.log(fruits.length); // 3

JavaScript arrays zero-indexed होते हैं, यानी पहला element index 0 पर होता है।

Array में Items Add या Remove करना

Code
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

Code
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
MethodUse
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 करता है।

Code
const numbers = [1, 2, 3];

const result = numbers.map(number => number * 2);

console.log(result); // [2, 4, 6]
Code
const numbers = [1, 2, 3];

const result = numbers.forEach(number => {
  console.log(number);
});

console.log(result); // undefined

Objects#

Object related data को key-value pairs में store करता है।

Code
const user = {
  name: "Aman",
  age: 25,
  city: "Chandigarh",
};

console.log(user.name);
console.log(user["city"]);

Object Properties Update करना

Code
const user = {
  name: "Aman",
  age: 25,
};

user.age = 26;
user.email = "aman@example.com";

console.log(user);

Object Methods

Code
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

Code
const user = {
  name: "Aman",
  age: 25,
};

console.log(Object.keys(user));
console.log(Object.values(user));
console.log(Object.entries(user));
MethodResult
Object.keys()Property keys का array
Object.values()Property values का array
Object.entries()Key-value pairs का array
Object.hasOwn()Object की own property check करना

Example:

Code
console.log(Object.hasOwn(user, "name")); // true

Destructuring#

Destructuring से arrays और objects की values को variables में conveniently extract कर सकते हैं।

Array Destructuring

Code
const colors = ["Red", "Green", "Blue"];

const [first, second] = colors;

console.log(first); // Red
console.log(second); // Green

Object Destructuring

Code
const user = {
  name: "Aman",
  age: 25,
};

const { name, age } = user;

console.log(name);
console.log(age);

Renaming Properties

Code
const user = {
  name: "Aman",
};

const { name: userName } = user;

console.log(userName);

Spread और Rest Operators#

Spread (...) iterable या object की properties को expand करने में मदद करता है।

Spread with Arrays

Code
const first = [1, 2];
const second = [3, 4];

const combined = [...first, ...second];

console.log(combined); // [1, 2, 3, 4]

Spread with Objects

Code
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 करता है।
Code
const numbers = [10, 20, 30];

console.log(...numbers); // 10 20 30
Code
function showItems(first, ...remaining) {
  console.log(first);
  console.log(remaining);
}

showItems("A", "B", "C");

Optional Chaining (?.)#

Optional chaining nested property access करते समय null या undefined की वजह से होने वाले errors से बचने में मदद करती है।

Code
const user = {
  profile: {
    name: "Aman",
  },
};

console.log(user.profile?.name); // Aman
console.log(user.address?.city); // undefined

Optional 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 करना

Code
const title = document.getElementById("title");
const button = document.querySelector("button");
const items = document.querySelectorAll(".item");
MethodUse
getElementById()ID से element select करना
querySelector()CSS selector से पहला matching element
querySelectorAll()सभी matching elements का static NodeList

Text Change करना

Code
<h2 id="title">Old Title</h2>
Code
const title = document.getElementById("title");

title.textContent = "New Title";

CSS Class Add या Remove करना

Code
const box = document.querySelector(".box");

box.classList.add("active");
box.classList.remove("hidden");
box.classList.toggle("highlight");

HTML Element Create करना

Code
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

Code
<button id="clickButton">Click Me</button>
<p id="output"></p>
Code
const button = document.getElementById("clickButton");
const output = document.getElementById("output");

button.addEventListener("click", () => {
  output.textContent = "Button clicked!";
});

Input Event

Code
<input id="nameInput" placeholder="Enter your name">
<p id="greeting"></p>
Code
const input = document.getElementById("nameInput");
const greeting = document.getElementById("greeting");

input.addEventListener("input", () => {
  greeting.textContent = `Hello, ${input.value}`;
});

Form Submit Event

Code
<form id="signupForm">
  <input id="email" type="email" required>
  <button type="submit">Submit</button>
</form>
Code
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 होता है।

Code
const user = {
  name: "Aman",
  age: 25,
};

Object को JSON String में Convert करना

Code
const jsonString = JSON.stringify(user);

console.log(jsonString);

Output:

Code
{"name":"Aman","age":25}

JSON String को Object में Convert करना

Code
const jsonString = '{"name":"Aman","age":25}';

const data = JSON.parse(jsonString);

console.log(data.name); // Aman

Invalid JSON parse करने पर error आ सकता है। Untrusted JSON parse करते समय error handling use करें।

JavaScript Modules: import और export#

Modules code को अलग-अलग files में organize करने में मदद करते हैं।

Export

math.js:

Code
export function add(a, b) {
  return a + b;
}

export const PI = 3.14159;

Import

main.js:

Code
import { add, PI } from "./math.js";

console.log(add(10, 20));
console.log(PI);

Browser में modules use करते समय HTML में:

Code
<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 कर सकते हैं।

Code
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 में चलना चाहिए।

Code
try {
  console.log("Processing...");
} catch (error) {
  console.error(error);
} finally {
  console.log("Finished");
}

Errors को बिना समझे silently ignore न करें।

Synchronous और Asynchronous JavaScript#

Synchronous code सामान्यतः statements को क्रम से execute करता है।

Code
console.log("First");
console.log("Second");
console.log("Third");

Output:

Code
First
Second
Third

Asynchronous operations में किसी operation के complete होने का इंतजार करते हुए बाकी code को आगे चलने दिया जा सकता है।

Example:

Code
console.log("Start");

setTimeout(() => {
  console.log("Timer finished");
}, 1000);

console.log("End");

Output:

Code
Start
End
Timer finished

setTimeout() callback को बाद के लिए schedule करता है। यह JavaScript के event loop और browser/host runtime के साथ काम करता है।

Promises#

Promise asynchronous operation के eventual success या failure को represent करता है।

Promise की तीन states:

  • pending
  • fulfilled
  • rejected

Example:

Code
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));
MethodUse
.then()Successful result handle करना
.catch()Rejection/error handle करना
.finally()Settlement के बाद cleanup करना

async और await#

async/await Promise-based asynchronous code को readable तरीके से लिखने में मदद करता है।

Code
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

Code
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

Code
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

Code
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 हो सकता है।

Code
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

Code
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 किया गया है।

Code
const user = {
  name: "Aman",

  greet() {
    console.log(this.name);
  },
};

user.greet(); // Aman

Regular 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 करता है।

Code
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)); // true

Array से duplicate values हटाने का example:

Code
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 की हो सकती हैं।

Code
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); // 2

JavaScript Best Practices#

  • By default const use करें; 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 करने के लिए textContent prefer करें।
  • 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 करना

Code
const age = 20;

console.log(age === 20); // true

= assignment के लिए है, जबकि === strict equality comparison के लिए है।

2. String और Number को Mix करना

Code
console.log("10" + 5); // "105"
console.log(Number("10") + 5); // 15

3. const को Immutable समझना

Code
const items = ["A", "B"];

items.push("C"); // Allowed

// items = ["X"]; // Error

4. Array Method का Return Value भूलना

Code
const numbers = [1, 2, 3];

const doubled = numbers.map(number => number * 2);

console.log(doubled);

5. fetch() में HTTP Status Check न करना

Code
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

Code
const button = document.querySelector("#missingButton");

if (button) {
  button.addEventListener("click", () => {
    console.log("Clicked");
  });
}

अगर selector matching element नहीं ढूँढता, तो querySelector() null return करता है।

JavaScript Quick Reference#

TaskSyntax
Variable declare करनाlet count = 0;
Constant declare करनाconst name = "Aman";
Console outputconsole.log(value);
Functionfunction greet() {}
Arrow functionconst add = (a, b) => a + b;
Conditionif (condition) {}
Loopfor (const item of items) {}
Array lengthitems.length
Array transformitems.map(callback)
Array filteritems.filter(callback)
Object propertyuser.name
Destructuringconst { name } = user;
Spreadconst copy = [...items];
DOM selectdocument.querySelector(".item")
Click eventelement.addEventListener("click", callback)
JSON stringifyJSON.stringify(data)
JSON parseJSON.parse(text)
Promise handlerpromise.then().catch()
Async functionasync function load() {}
Fetch APIawait fetch(url)
Error handlingtry { } catch (error) { }
Module importimport { add } from "./math.js";
Module exportexport function add() {}

JavaScript Practice Exercises#

Beginner Exercises

  1. दो numbers को add करके result print करें।
  2. एक variable में age store करें और if...else से adult/minor check करें।
  3. for loop से 1 से 10 तक numbers print करें।
  4. एक function बनाएं जो दो numbers का product return करे।
  5. एक array में पाँच fruits रखें और उन्हें for...of से print करें।

Intermediate Exercises

  1. Array में से केवल even numbers निकालने के लिए filter() use करें।
  2. Array के सभी numbers का sum reduce() से calculate करें।
  3. Object में name, email और city store करें और values print करें।
  4. Button click करने पर webpage का text change करें।
  5. एक JSON string को object में parse करें और उसकी properties display करें।

Advanced Exercises

  1. async/await से API data fetch करें और errors handle करें।
  2. एक reusable function बनाएं जो array से duplicate values remove करे।
  3. User class और Admin subclass बनाएं।
  4. एक form बनाएं जिसमें input validation और submit event handling हो।
  5. दो JavaScript modules बनाएं और import/export से उन्हें connect करें।

JavaScript Knowledge Check#

  1. JavaScript का मुख्य use क्या है?
  2. let, const और var में क्या difference है?
  3. Primitive data types कौन-कौन से हैं?
  4. == और === में क्या अंतर है?
  5. map() और forEach() का return behavior कैसे अलग है?
  6. Object destructuring क्यों useful है?
  7. Spread और rest syntax में क्या difference है?
  8. DOM क्या है?
  9. addEventListener() किसलिए use होता है?
  10. Promise की तीन states क्या हैं?
  11. async function क्या return करता है?
  12. fetch() response के साथ response.ok क्यों check करना चाहिए?
  13. JavaScript modules में import और export का क्या role है?
  14. null और undefined में क्या difference है?
  15. const object की 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:

  1. HTML
  2. CSS
  3. JavaScript
  4. JSON
  5. Fetch / REST APIs
  6. Node.js
  7. npm
  8. Build Tools (Vite)
  9. TypeScript
  10. React

आगे बढ़ने से पहले इस Cheat Sheet के beginner exercises खुद run करें। इससे JSON और API integration सीखने के लिए आपकी foundation मजबूत होगी।