██╗███████╗ ██████╗██╗ ██╗███████╗ █████╗ ████████╗ ███████╗██╗ ██╗███████╗███████╗████████╗
██║██╔════╝ ██╔════╝██║ ██║██╔════╝██╔══██╗╚══██╔══╝ ██╔════╝██║ ██║██╔════╝██╔════╝╚══██╔══╝
██║███████╗ ██║ ███████║█████╗ ███████║ ██║ ███████╗███████║█████╗ █████╗ ██║
██ ██║╚════██║ ██║ ██╔══██║██╔══╝ ██╔══██║ ██║ ╚════██║██╔══██║██╔══╝ ██╔══╝ ██║
╚█████╔╝███████║ ╚██████╗██║ ██║███████╗██║ ██║ ██║ ███████║██║ ██║███████╗███████╗ ██║
╚════╝ ╚══════╝ ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚══════╝╚══════╝ ╚═╝
🌍 Bilingual · دوزبانه | 🇺🇸 English + 🇮🇷 فارسی
🇺🇸 Your all-in-one JavaScript reference — from variables to proxies, written for humans.
🇮🇷 راهنمای جامع جاوااسکریپت — از متغیرها تا پراکسی، نوشتهشده برای انسانها.
| # | Topic 🇺🇸 | موضوع 🇮🇷 |
|---|---|---|
| 01 | Basics & Output | مفاهیم پایه |
| 02 | Variables & Data Types | متغیرها و انواع داده |
| 03 | Operators & Conditions | عملگرها و شرطها |
| 04 | Loops | حلقهها |
| 05 | Functions | توابع |
| 06 | Objects & Arrays | اشیاء و آرایهها |
| 07 | Advanced Array Methods | متدهای پیشرفته آرایه |
| 08 | Destructuring | واپاشی |
| 09 | Spread & Rest | اسپرد و رست |
| 10 | Recursion | توابع بازگشتی |
| 11 | Error Handling | مدیریت خطا |
| 12 | Modules | ماژولها |
| 13 | Classes & OOP | کلاسها و شیگرایی |
| 14 | Event Loop | حلقه رویداد |
| 15 | DOM Manipulation | تعامل با DOM |
| 16 | Optional Chaining & Nullish Coalescing | زنجیره اختیاری |
| 17 | Promises & Async/Await | پرامیس و ناهمزمانی |
| 18 | Set & Map | ست و مپ |
| 19 | Generators | مولدها |
| 20 | Symbol | سیمبول |
| 21 | Proxy & Reflect | پراکسی و ریفلکت |
| 22 | Web APIs | وب ایپیآی |
| 23 | Scope & Shadowing | اسکوپ و سایهزنی |
| 24 | this Keyword | کلیدواژه this |
| 25 | Memory & GC | مدیریت حافظه |
| 26 | Clean Code | کدنویسی تمیز |
| 27 | Design Patterns | الگوهای طراحی |
🇺🇸 Every JavaScript journey starts here — printing to the console.
🇮🇷 هر سفر جاوااسکریپتی از اینجا شروع میشه — چاپ کردن در کنسول.
console.log("Hello, World! 🌍"); // General output
console.warn("⚠️ Be careful!"); // Warning — هشدار
console.error("❌ Something broke!"); // Error — خطا
console.table([{ name: "Ali", age: 25 }]); // Table output — خروجی جدولی💡 Tip 🇺🇸: Open DevTools (F12) and go to the Console tab to see output.
💡 نکته 🇮🇷: با زدن F12 و رفتن به تب Console میتونید خروجی رو ببینید.
🇺🇸 Variables are containers for storing data. JavaScript has 3 ways to declare them — and knowing the difference matters.
🇮🇷 متغیرها ظرفهایی برای نگهداری داده هستند. جاوااسکریپت ۳ راه برای تعریف دارد — و دونستن تفاوتشون مهمه.
var name = "Old way 👴"; // Function-scoped, avoid in modern code
let count = 0; // Block-scoped, can be reassigned — قابل تغییر
const PI = 3.14159; // Block-scoped, cannot be reassigned — ثابتlet str = "Hello"; // 📝 String — رشته
let num = 42; // 🔢 Number — عدد
let float = 3.14; // 🔢 Float — اعشاری
let bool = true; // ✅ Boolean — منطقی
let nothing = null; // 🚫 Null — هیچ
let undef; // ❓ Undefined — تعریفنشده
let sym = Symbol("id"); // 🔑 Symbol — یکتا
let big = 9007199254740991n; // 🦕 BigInt — عدد بزرگ
let person = { name: "Sara", age: 30 }; // 📦 Object — شیء
let colors = ["red", "green", "blue"]; // 📋 Array — آرایهtypeof |
Returns |
|---|---|
typeof "hello" |
"string" |
typeof 42 |
"number" |
typeof true |
"boolean" |
typeof null |
"object" |
typeof undefined |
"undefined" |
🇺🇸 Operators let you compare, calculate, and make decisions.
🇮🇷 عملگرها به شما اجازه میدن مقایسه، محاسبه و تصمیمگیری کنید.
// ➕ Arithmetic — حسابی
let sum = 10 + 5; // 15
let mod = 10 % 3; // 1 (remainder — باقیمانده)
let pow = 2 ** 8; // 256 (exponent — توان)
// 🔍 Comparison — مقایسهای
5 == "5" // true (loose — فقط مقدار)
5 === "5" // false (strict — مقدار + نوع) ✅ Always prefer this!
5 !== 3 // true
// 🧠 Logical — منطقی
true && false // false (AND)
true || false // true (OR)
!true // false (NOT)const age = 20;
// if / else if / else
if (age < 13) {
console.log("Child 👶");
} else if (age < 18) {
console.log("Teenager 🧒");
} else {
console.log("Adult 🧑");
}
// Ternary — سهتایی (one-liner)
const status = age >= 18 ? "Adult ✅" : "Minor ❌";
// Switch
switch (age) {
case 18: console.log("Just turned 18!"); break;
default: console.log("Some other age");
}🇺🇸 Loops let you repeat actions without repeating yourself.
🇮🇷 حلقهها به شما اجازه میدن بدون تکرار کد، عملیات رو تکرار کنید.
// Classic for — کلاسیک
for (let i = 0; i < 5; i++) {
console.log(`Step ${i} 🚶`);
}
// while — تا زمانی که
let energy = 3;
while (energy > 0) {
console.log(`Energy left: ${energy--} ⚡`);
}
// do...while — حداقل یک بار اجرا میشه
let tries = 0;
do {
console.log(`Try #${++tries}`);
} while (tries < 3);
// for...of — برای آرایهها و iterableها ✅
for (const fruit of ["🍎", "🍌", "🍇"]) {
console.log(fruit);
}
// for...in — برای کلیدهای شیء
for (const key in { name: "Ali", city: "Tehran" }) {
console.log(key); // name, city
}🇺🇸 Functions are reusable blocks of code — the backbone of any program.
🇮🇷 توابع بلوکهای قابلاستفادهی مجدد هستند — ستون فقرات هر برنامه.
// 📌 Classic declaration — اعلان کلاسیک
function greet(name) {
return `Hello, ${name}! 👋`;
}
// 📌 Function expression — تابع در متغیر
const greet2 = function(name) {
return `Hey, ${name}!`;
};
// ⚡ Arrow function — تابع فلشی (modern & clean)
const greet3 = (name) => `Hi, ${name}! 🎉`;
// 🛡️ Default parameters — پارامتر پیشفرض
const welcome = (name = "Guest") => `Welcome, ${name}!`;
// 🔮 Higher-order function — تابع مرتبهبالا
const multiply = (factor) => (number) => number * factor;
const double = multiply(2);
console.log(double(5)); // 10⚡ Arrow functions don't have their own
this— keep that in mind for OOP! ⚡ توابع فلشیthisمخصوص به خود ندارند — در شیگرایی دقت کنید!
🇺🇸 Objects store key-value pairs; arrays store ordered lists.
🇮🇷 اشیاء جفتهای کلید-مقدار ذخیره میکنند؛ آرایهها لیستهای مرتب.
// 📦 Object — شیء
const person = {
name: "Sara",
age: 30,
skills: ["JS", "CSS", "HTML"],
greet() {
console.log(`Hi, I'm ${this.name} 👩💻`);
}
};
person.greet(); // Hi, I'm Sara 👩💻
console.log(person["name"]); // Sara
// 📋 Array — آرایه
const nums = [10, 20, 30];
nums.push(40); // Add end — اضافه به آخر → [10,20,30,40]
nums.pop(); // Remove end — حذف آخر → [10,20,30]
nums.unshift(0); // Add start — اضافه به اول → [0,10,20,30]
nums.shift(); // Remove start — حذف اول → [10,20,30]
nums.forEach((n, i) => console.log(`[${i}] = ${n}`));🇺🇸 These methods are the secret weapon of every JS developer. Master them.
🇮🇷 این متدها سلاح مخفی هر توسعهدهنده JS هستند. تسلط پیدا کنید.
const nums = [1, 2, 3, 4, 5, 6];
// 🗺️ map — تبدیل هر عنصر
const doubled = nums.map(n => n * 2);
// [2, 4, 6, 8, 10, 12]
// 🔍 filter — فیلتر کردن
const evens = nums.filter(n => n % 2 === 0);
// [2, 4, 6]
// 🧮 reduce — تجمیع به یک مقدار
const total = nums.reduce((acc, n) => acc + n, 0);
// 21
// 🔎 find / findIndex
const firstBig = nums.find(n => n > 3); // 4
const idx = nums.findIndex(n => n > 3); // 3
// ✅ some / every
nums.some(n => n > 5); // true — حداقل یکی
nums.every(n => n > 0); // true — همه
// 🪄 flat / flatMap
[[1, 2], [3, 4]].flat(); // [1, 2, 3, 4]
[1, 2, 3].flatMap(n => [n, n * 2]); // [1,2, 2,4, 3,6]
// 🔀 sort
["banana", "apple", "cherry"].sort(); // ["apple", "banana", "cherry"]
[3, 1, 2].sort((a, b) => a - b); // [1, 2, 3]🇺🇸 Pull values out of objects and arrays cleanly and elegantly.
🇮🇷 مقادیر رو از اشیاء و آرایهها تمیز و زیبا بیرون بکشید.
// 📦 Object destructuring — واپاشی شیء
const { name, age, city = "Tehran" } = { name: "Ali", age: 30 };
// ↑ default value — مقدار پیشفرض
// Rename on the fly — تغییر نام
const { name: fullName } = { name: "Sara" };
console.log(fullName); // "Sara"
// 📋 Array destructuring — واپاشی آرایه
const [first, second, ...rest] = [10, 20, 30, 40, 50];
// first=10, second=20, rest=[30,40,50]
// 🔄 Swap variables — جابهجایی متغیرها (JS magic!)
let a = 1, b = 2;
[a, b] = [b, a];
// a=2, b=1 ✨
// 🎯 In function parameters — در پارامترهای تابع
function display({ name, age }) {
console.log(`${name} is ${age} years old`);
}
display({ name: "Ali", age: 25 });🇺🇸
...does two things depending on context — spread things out or gather them up.🇮🇷
...بسته به کاربرد دو کار میکنه — پخش کردن یا جمعآوری.
// 🌊 Spread — پخش کردن
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
// Merge objects — ادغام اشیاء
const defaults = { theme: "dark", lang: "en" };
const userPrefs = { lang: "fa", fontSize: 16 };
const config = { ...defaults, ...userPrefs };
// { theme: "dark", lang: "fa", fontSize: 16 }
// Copy arrays & objects — کپی
const copy = [...arr1]; // independent copy — کپی مستقل
// 🎒 Rest — جمعآوری
function sum(first, ...others) {
return first + others.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3, 4, 5); // 15🇺🇸 A function that calls itself — powerful for tree traversal, fractals, and math.
🇮🇷 تابعی که خودش رو صدا میزنه — قدرتمند برای درختها، فراکتالها و ریاضیات.
// 🔢 Factorial — فاکتوریل
function factorial(n) {
if (n <= 1) return 1; // 🛑 Base case — شرط پایه
return n * factorial(n - 1);
}
factorial(5); // 120 (5 × 4 × 3 × 2 × 1)
// 🌲 Flatten nested array — یکسانسازی آرایه تودرتو
function flatten(arr) {
return arr.reduce((flat, item) =>
Array.isArray(item) ? [...flat, ...flatten(item)] : [...flat, item], []
);
}
flatten([1, [2, [3, [4]]]]); // [1, 2, 3, 4]
⚠️ Always define a base case to avoid infinite loops!⚠️ همیشه شرط پایه تعریف کنید تا حلقه بینهایت نشه!
🇺🇸 Don't let your app crash — catch errors gracefully.
🇮🇷 اجازه نده اپت کرش کنه — خطاها رو زیبا مدیریت کن.
// 🧱 try / catch / finally
try {
const result = JSON.parse("{ invalid json }"); // 💥 throws!
} catch (error) {
console.error(`❌ Error: ${error.message}`);
} finally {
console.log("✅ Always runs — همیشه اجرا میشه");
}
// 🎯 Custom error — خطای سفارشی
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
function validateAge(age) {
if (age < 0) throw new ValidationError("Age cannot be negative! 🚫");
return age;
}
try {
validateAge(-5);
} catch (e) {
if (e instanceof ValidationError) {
console.warn(`Validation failed: ${e.message}`);
}
}🇺🇸 Split your code into files — keep things organized and reusable.
🇮🇷 کدت رو به فایلهای جداگانه تقسیم کن — منظم و قابلاستفادهی مجدد.
// 📤 math.js — export
export const PI = 3.14159;
export function add(a, b) { return a + b; }
export function subtract(a, b) { return a - b; }
export default function multiply(a, b) { return a * b; } // default export
// 📥 main.js — import
import multiply, { PI, add, subtract } from './math.js';
// default ↑ named exports ↑
// 🌐 Import everything — وارد کردن همه چیز
import * as MathUtils from './math.js';
MathUtils.add(2, 3); // 5
// 🔄 Re-export — صادر کردن مجدد
export { add, subtract } from './math.js';🇺🇸 Classes are blueprints for creating objects — the foundation of object-oriented programming.
🇮🇷 کلاسها طرحوارههایی برای ساخت اشیاء هستند — پایه برنامهنویسی شیگرا.
class Animal {
#name; // 🔒 Private field — فیلد خصوصی
constructor(name, sound) {
this.#name = name;
this.sound = sound;
}
get name() { return this.#name; } // Getter
speak() {
return `${this.#name} says: ${this.sound}! 🔊`;
}
static create(name, sound) { // 🏭 Factory — کارخانه
return new Animal(name, sound);
}
}
// 🧬 Inheritance — وراثت
class Dog extends Animal {
constructor(name) {
super(name, "Woof"); // Call parent constructor — فراخوانی سازنده والد
}
fetch() {
return `${this.name} fetches the ball! 🎾`;
}
}
const dog = new Dog("Rex");
console.log(dog.speak()); // Rex says: Woof! 🔊
console.log(dog.fetch()); // Rex fetches the ball! 🎾🇺🇸 JavaScript is single-threaded — the Event Loop is how it handles async operations without blocking.
🇮🇷 جاوااسکریپت تکرشتهای است — حلقه رویداد روشی است که بدون مسدود کردن، عملیات ناهمزمان رو مدیریت میکنه.
console.log("1️⃣ Start");
setTimeout(() => console.log("3️⃣ Timeout (macrotask)"), 0);
Promise.resolve().then(() => console.log("2️⃣ Promise (microtask)"));
console.log("1️⃣ End");
// Output order — ترتیب خروجی:
// 1️⃣ Start
// 1️⃣ End
// 2️⃣ Promise (microtask) ← runs before setTimeout!
// 3️⃣ Timeout (macrotask)📊 Priority — اولویت:
┌─────────────────────────────────┐
│ Call Stack (synchronous) 🥇 │
│ Microtask Queue (Promises) 🥈 │
│ Macrotask Queue (setTimeout) 🥉 │
└─────────────────────────────────┘
🇺🇸 The DOM is the live representation of your HTML — JS can read and change it in real time.
🇮🇷 DOM نمایش زنده HTML شماست — JS میتونه اون رو در لحظه بخونه و تغییر بده.
// 🔍 Select elements — انتخاب عناصر
const title = document.getElementById("title");
const btn = document.querySelector(".btn"); // first match
const items = document.querySelectorAll(".item"); // all matches — همه
// ✏️ Modify — تغییر
title.textContent = "New Title ✨";
title.style.color = "#f0a500";
title.classList.add("highlight");
title.classList.toggle("active");
// 🏗️ Create & insert — ساخت و درج
const newEl = document.createElement("p");
newEl.textContent = "I was born from JS! 🐣";
document.body.appendChild(newEl);
// 👂 Events — رویدادها
btn.addEventListener("click", (event) => {
console.log("Clicked! 🖱️", event.target);
});
// 🎯 Event delegation — نیابت رویداد (efficient for dynamic lists)
document.querySelector("ul").addEventListener("click", (e) => {
if (e.target.tagName === "LI") {
e.target.classList.toggle("done");
}
});🇺🇸 Access deeply nested properties safely without crashing your app.
🇮🇷 بدون کرش کردن، به ویژگیهای تودرتو دسترسی ایمن داشته باشید.
const user = {
name: "Sara",
address: {
city: "Tehran",
zip: "12345"
},
getAvatar: () => "👩"
};
// ✅ Optional Chaining ?.
console.log(user?.address?.city); // "Tehran"
console.log(user?.phone?.number); // undefined (no crash! 🛡️)
console.log(user?.getAvatar?.()); // "👩"
console.log(user?.getPhoneNumber?.()); // undefined
// 🤝 Nullish Coalescing ??
const city = user?.address?.city ?? "Unknown City"; // "Tehran"
const country = user?.address?.country ?? "Iran"; // "Iran"
// ⚡ Combine for powerful patterns — ترکیب برای الگوهای قدرتمند
const displayName = user?.profile?.displayName ?? user?.name ?? "Anonymous";💡
??only falls back fornull/undefined, not0or""— unlike||! 💡??فقط برایnullوundefinedجایگزین میشه، نه0یا""— بر خلاف||!
🇺🇸 Handle asynchronous operations elegantly — no more callback hell.
🇮🇷 عملیات ناهمزمان رو زیبا مدیریت کنید — دیگه جهنم callback نه.
// 🤝 Promise — وعده
const fetchUser = (id) => new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) resolve({ id, name: "Ali" });
else reject(new Error("Invalid ID ❌"));
}, 1000);
});
// 🔗 Promise chaining — زنجیره وعدهها
fetchUser(1)
.then(user => ({ ...user, role: "admin" }))
.then(user => console.log("User:", user))
.catch(err => console.error("Error:", err.message))
.finally(() => console.log("Done ✅"));
// ⚡ async/await — همزماننما
async function loadUserData(id) {
try {
const user = await fetchUser(id);
console.log(`Loaded: ${user.name} 🎉`);
return user;
} catch (error) {
console.error(`Failed: ${error.message} 💥`);
}
}
// 🚀 Run in parallel — اجرای موازی
async function loadAll() {
const [user1, user2] = await Promise.all([fetchUser(1), fetchUser(2)]);
console.log(user1, user2);
}
// 🏁 Race — مسابقه (first to finish wins)
const fastest = await Promise.race([fetchUser(1), fetchUser(2)]);🇺🇸 Specialized data structures that solve problems arrays and objects can't handle cleanly.
🇮🇷 ساختارهای دادهای تخصصی که مشکلاتی رو حل میکنند که آرایهها و اشیاء بهخوبی حلشون نمیکنند.
// 🎯 Set — مجموعه (unique values only — فقط مقادیر یکتا)
const tags = new Set(["js", "css", "js", "html", "css"]);
// Set {"js", "css", "html"} — duplicates removed ✨
tags.add("react");
tags.delete("css");
tags.has("js"); // true
console.log([...tags]); // Convert to array — تبدیل به آرایه
// 🗺️ Map — نقشه (any key type — هر نوع کلید)
const scores = new Map();
scores.set("Alice", 95);
scores.set("Bob", 87);
scores.set({ id: 1 }, "object key works too! 🤯");
scores.get("Alice"); // 95
scores.has("Bob"); // true
scores.size; // 3
// Iterate — پیمایش
for (const [name, score] of scores) {
console.log(`${name}: ${score}`);
}🇺🇸 Functions that can pause and resume — perfect for lazy evaluation and infinite sequences.
🇮🇷 توابعی که میتونند مکث و ادامه بدن — عالی برای ارزیابی تنبل و دنبالههای بینهایت.
// 🏭 Generator function — تابع مولد
function* counter(start = 0) {
while (true) {
yield start++; // Pause here each time — هر بار اینجا مکث میکنه
}
}
const count = counter(1);
count.next().value; // 1
count.next().value; // 2
count.next().value; // 3 (infinite! ♾️)
// 🌊 Fibonacci — فیبوناچی
function* fibonacci() {
let [a, b] = [0, 1];
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
const fib = fibonacci();
Array.from({ length: 8 }, () => fib.next().value);
// [0, 1, 1, 2, 3, 5, 8, 13] 🐚🇺🇸 Guaranteed unique identifiers — great for object keys that won't collide.
🇮🇷 شناسههای تضمینی یکتا — عالی برای کلیدهای شیء که تداخل نخواهند داشت.
const ID = Symbol("id");
const SECRET = Symbol("secret");
const user = {
name: "Ali",
[ID]: 42, // Symbol key — کلید سیمبول
[SECRET]: "🤫",
};
console.log(user[ID]); // 42
console.log(user[SECRET]); // 🤫
// Symbols are hidden from most enumeration — سیمبولها از اکثر پیمایشها مخفی هستند
Object.keys(user); // ["name"] only!
Object.getOwnPropertySymbols(user); // [Symbol(id), Symbol(secret)]
// 🌍 Global symbols — سیمبولهای سراسری
const s1 = Symbol.for("shared");
const s2 = Symbol.for("shared");
s1 === s2; // true ✅ (same global symbol)🇺🇸 Intercept and customize object operations — the ultimate metaprogramming tool.
🇮🇷 رهگیری و سفارشیسازی عملیات شیء — ابزار نهایی متاپروگرامینگ.
const validator = {
set(target, prop, value) {
if (prop === "age" && typeof value !== "number") {
throw new TypeError("Age must be a number! 🔢");
}
if (prop === "age" && value < 0) {
throw new RangeError("Age cannot be negative! 🚫");
}
return Reflect.set(target, prop, value); // Use Reflect for safe setting
},
get(target, prop) {
return prop in target
? target[prop]
: `⚠️ Property '${prop}' doesn't exist`;
}
};
const person = new Proxy({}, validator);
person.age = 25; // ✅ OK
person.name = "Sara"; // ✅ OK
console.log(person.age); // 25
console.log(person.job); // ⚠️ Property 'job' doesn't exist
// person.age = "old"; // 💥 TypeError: Age must be a number!🇺🇸 Built-in browser superpowers — fetch data, store locally, draw graphics, and more.
🇮🇷 قدرتهای داخلی مرورگر — دریافت داده، ذخیره محلی، رسم گرافیک و بیشتر.
// 🌍 Fetch API — دریافت داده
async function getPost(id) {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
if (!res.ok) throw new Error(`HTTP Error: ${res.status}`);
return res.json();
}
// 💾 localStorage — ذخیرهسازی محلی (persists after tab close)
localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme"); // "dark"
localStorage.removeItem("theme");
// 🔄 sessionStorage — ذخیرهسازی جلسه (cleared on tab close)
sessionStorage.setItem("draft", JSON.stringify({ text: "Hello..." }));
// ⏰ Timers — تایمرها
const timer = setTimeout(() => console.log("Later! ⏰"), 2000);
clearTimeout(timer); // Cancel — لغو
const interval = setInterval(() => console.log("Tick 🕐"), 1000);
clearInterval(interval); // Stop — متوقف کردن
// 📋 Clipboard — کلیپبورد
navigator.clipboard.writeText("Copied! 📋");🇺🇸 Scope determines where variables live — shadowing happens when inner vars hide outer ones.
🇮🇷 اسکوپ تعیین میکند متغیرها کجا زندگی میکنند — سایهزنی وقتی رخ میدهد که متغیر داخلی متغیر خارجی را پنهان میکند.
const color = "blue 🔵"; // Global scope — اسکوپ سراسری
function paintRoom() {
const color = "red 🔴"; // Local scope — shadows global! / سایه میزند
console.log(color); // "red 🔴"
if (true) {
const color = "green 🟢"; // Block scope — shadows local!
let temp = "only here"; // Block-scoped
console.log(color); // "green 🟢"
}
// console.log(temp); // ❌ ReferenceError — not accessible here
console.log(color); // "red 🔴" (back to function scope)
}
paintRoom();
console.log(color); // "blue 🔵" (global untouched)📊 Scope chain — زنجیره اسکوپ:
Block → Function → Module → Global
🇺🇸
thisrefers to the object that is calling the function — context-dependent.🇮🇷
thisبه شیئی اشاره میکند که تابع را فراخوانی میکند — وابسته به زمینه.
// 📦 In an object method — در متد شیء
const car = {
brand: "Toyota 🚗",
getBrand() {
return this.brand; // this = car
},
getBrandArrow: () => {
return this?.brand; // ⚠️ Arrow: this = outer (not car!)
}
};
console.log(car.getBrand()); // "Toyota 🚗"
console.log(car.getBrandArrow()); // undefined ⚠️
// 🎨 Explicit binding — اتصال صریح
function introduce(greeting) {
return `${greeting}, I'm ${this.name}`;
}
const person = { name: "Ali" };
introduce.call(person, "Hello"); // bind + call immediately
introduce.apply(person, ["Salaam"]); // same but args as array
const boundFn = introduce.bind(person); // returns new function
boundFn("Hey"); // call later🇺🇸 JavaScript manages memory automatically — but you can still create leaks if you're not careful.
🇮🇷 جاوااسکریپت حافظه رو بهصورت خودکار مدیریت میکنه — اما اگه دقت نکنید، میتونید نشت ایجاد کنید.
// ✅ Good — Object gets collected when out of scope
function createTemp() {
const bigData = new Array(1_000_000).fill("🗑️");
return bigData.length; // Only return what's needed
}
// 🚨 Potential memory leak — نشت حافظه احتمالی
const cache = {};
function addToCache(key, value) {
cache[key] = value; // Grows forever if not managed! 📈
}
// ✅ Use WeakMap for object-keyed caches — از WeakMap برای کشهای کلید-شیء استفاده کنید
const weakCache = new WeakMap();
let obj = { id: 1 };
weakCache.set(obj, "data");
obj = null; // 🎉 Memory freed automatically! — حافظه آزاد میشه خودکار💡 WeakMap and WeakSet hold weak references — objects inside can be garbage collected. 💡 WeakMap و WeakSet مراجع ضعیف نگه میدارند — اشیاء داخل میتوانند جمعآوری شوند.
🇺🇸 Code is read more than it's written — make it readable, predictable, and honest.
🇮🇷 کد بیشتر خونده میشه تا نوشته — خوانا، قابلپیشبینی و صادق باشید.
// ❌ Bad — بد
function c(a,b){return a+b;}
const x = d ? f(d) : null;
// ✅ Good — خوب
function calculateTotal(price, tax) {
return price + tax;
}
const discountedPrice = hasDiscount ? applyDiscount(price) : null;
// ❌ Magic numbers — اعداد جادویی
if (status === 3) { /* ... */ }
// ✅ Named constants — ثابتهای نامدار
const STATUS_APPROVED = 3;
if (status === STATUS_APPROVED) { /* ... */ }
// ❌ Deeply nested — تودرتوی عمیق
if (user) {
if (user.account) {
if (user.account.balance > 0) {
processPayment();
}
}
}
// ✅ Early return — برگشت زودهنگام (Guard clauses)
if (!user?.account?.balance > 0) return;
processPayment();🇺🇸 Proven solutions to common programming problems — stand on the shoulders of giants.
🇮🇷 راهحلهای اثباتشده برای مشکلات رایج برنامهنویسی — روی شانه غولها بایستید.
// 🏭 Factory Pattern — الگوی کارخانه
function createUser(name, role = "viewer") {
return {
name,
role,
permissions: role === "admin" ? ["read","write","delete"] : ["read"],
greet() { return `Hi, I'm ${name} (${role}) 👋`; }
};
}
const admin = createUser("Ali", "admin");
const viewer = createUser("Sara");
// 📦 Module Pattern — الگوی ماژول (encapsulation)
const ShoppingCart = (() => {
let items = []; // Private — خصوصی
return {
add(item) { items.push(item); },
remove(item) { items = items.filter(i => i !== item); },
getTotal() { return items.reduce((sum, i) => sum + i.price, 0); },
getCount() { return items.length; }
};
})();
ShoppingCart.add({ name: "Book 📚", price: 20 });
ShoppingCart.add({ name: "Pen 🖊️", price: 5 });
console.log(ShoppingCart.getTotal()); // 25
// 👀 Observer Pattern — الگوی ناظر
class EventEmitter {
#listeners = {};
on(event, callback) {
(this.#listeners[event] ??= []).push(callback);
}
emit(event, data) {
this.#listeners[event]?.forEach(cb => cb(data));
}
}
const emitter = new EventEmitter();
emitter.on("login", user => console.log(`${user} logged in! 🔐`));
emitter.emit("login", "Ali");| Resource 🇺🇸 | منبع 🇮🇷 |
|---|---|
| MDN Web Docs | مرجع کامل وب |
| javascript.info | آموزش از پایه تا پیشرفته |
| You Don't Know JS | کتاب عمیق JS |
| JS Visualizer | تجسم Event Loop |
"Any fool can write code that a computer can understand.
Good programmers write code that humans can understand."
— Martin Fowler
«هر احمقی میتواند کدی بنویسد که کامپیوتر بفهمد.
برنامهنویسان خوب کدی مینویسند که انسانها بفهمند.»
Made with ❤️ for the JS community | ساختهشده با ❤️ برای جامعه JS