مرجع کامل جاوا اسکریپت

مرجع سریع Syntax، متغیرها، عملگرها، Statements، توابع، اشیا، آرایه‌ها، رشته‌ها، اعداد، Math، Date، RegExp، Map و Set، Promise، JSON، DOM و Web APIs و Events.

مرجع Syntax

// متغیرها:
let mutable = 1;
const immutable = "ثابت";
var legacy = "قدیمی";  // ننویس!

// تابع:
function name(params) { }
const arrow = (a, b) => a + b;
const single = x => x * 2;
const method = function () { };

// شرط:
if (cond) { } else if { } else { }
cond ? valueA : valueB;
switch (x) { case 1: break; default: }

// حلقه:
for (let i = 0; i < n; i++) { }
for (const item of iterable) { }
for (const key in object) { }
while (cond) { }
do { } while (cond);

// کلاس:
class Name extends Parent {
    #private = 0;
    static count = 0;
    constructor() { super(); }
    method() { }
    get prop() { }
    set prop(v) { }
}

// خطا:
try { risky(); } catch (e) { } finally { }
throw new Error("message");

// ماژول:
import x from "./mod.js";
export const y = 1;
export default class { }

مرجع عملگرها

عملگرتوضیحمثال
+ - * / %حسابی7 % 3 → 1
**توان2 ** 8 → 256
++ --افزایش/کاهشx++
== !=مساوی با اجباربد بنویسید!
=== !==مساوی دقیق1 === "1" → false
< > <= >=مقایسه
&& || !منطقیa && b
??Nullishnull ?? 5 → 5
?.اختیاریobj?.x
...Spread/Rest[...arr]
typeofنوعtypeof x
instanceofنمونهx instanceof Array
inوجود"x" in obj
??= ||= &&=انتساب منطقیx ??= 5

مرجع اشیا (Object)

const obj = { a: 1, b: 2 };

// دسترسی:
obj.a;           // dot
obj["b"];        // bracket
obj?.c?.d;       // امن

// ساخت/تغییر:
obj.new = 3;
delete obj.a;

// بررسی:
"a" in obj;
obj.hasOwnProperty("a");
Object.hasOwn(obj, "a");

// کلیدها و مقادیر:
Object.keys(obj);      // ["b", "new"]
Object.values(obj);    // [2, 3]
Object.entries(obj);   // [["b",2],["new",3]]

// ساخت از entries:
Object.fromEntries([["x", 1]]);  // {x: 1}

// merge:
Object.assign({}, a, b);
const merged = { ...a, ...b };

// کپی عمیق:
structuredClone(obj);  // مدرن!
JSON.parse(JSON.stringify(obj));  // قدیمی

// freeze و seal:
Object.freeze(obj);  // کاملاً ثابت
Object.seal(obj);    // تغییر مقدار فقط

// ایجاد با prototype:
Object.create(proto);

// توصیف:
Object.getOwnPropertyDescriptor(obj, "key");
Object.defineProperty(obj, "key", {
    value: 1, writable: true, enumerable: true
});

// مقایسه:
JSON.stringify(a) === JSON.stringify(b);  // سریع
// مقایسه عمیق — کتابخانه یا دستی

مرجع آرایه‌ها (Array)

const arr = [1, 2, 3];

// افزودن/حذف:
arr.push(4);        // آخر
arr.pop();          // حذف آخر
arr.unshift(0);     // اول
arr.shift();        // حذف اول

// برش:
arr.slice(1, 2);    // [2] — کپی
arr.splice(1, 1);   // حذف واقعی

// تغییرناپذیر (ES2023):
arr.toSorted();
arr.toReversed();
arr.toSpliced(1, 1);
arr.with(0, "new");

// جست‌وجو:
arr.indexOf(2);
arr.includes(2);
arr.find(x => x > 1);
arr.findIndex(x => x > 1);
arr.findLast(x => x > 1);

// پیمایش:
arr.forEach(x => { });
arr.map(x => x * 2);
arr.filter(x => x > 1);
arr.reduce((a, b) => a + b, 0);
arr.reduceRight((a, b) => a - b);
arr.some(x => x > 2);
arr.every(x => x > 0);
arr.flat();
arr.flatMap(x => [x, x]);

// مرتب‌سازی:
arr.sort();                          // پیش‌فرض رشته
arr.sort((a, b) => a - b);           // عددی صعودی
arr.sort((a, b) => b - a);           // نزولی

// تبدیل:
arr.join("-");
Array.from("abc");                   // ["a","b","c"]
Array.of(1, 2, 3);
[...iterable];

// بررسی:
Array.isArray(arr);

// جایگشت:
arr.at(-1);                          // آخرین
arr.length;
arr.entries();
arr.keys();
arr.values();

مرجع رشته‌ها (String)

const str = "سلام دنیا";

// طول:
str.length;

// دسترسی:
str[0];
str.charAt(0);
str.at(-1);         // آخرین!
str.charCodeAt(0);
str.codePointAt(0);

// جست‌وجو:
str.indexOf("دنیا");
str.lastIndexOf("ا");
str.includes("سلام");
str.startsWith("س");
str.endsWith("ا");
str.search(/regex/);
str.match(/pattern/g);
str.matchAll(/p/g);

// استخراج:
str.slice(0, 4);
str.substring(0, 4);
str.substr(0, 4);   // منسوخ

// جایگزینی:
str.replace("a", "b");        // اولی
str.replaceAll("a", "b");     // همه
str.replace(/regex/g, "new");

// تقسیم:
str.split(" ");
str.split("");

// حروف:
str.toUpperCase();
str.toLowerCase();
str.trim();
str.trimStart();
str.trimEnd();
str.padStart(5, "0");
str.padEnd(5, "0");

// تکرار و ساخت:
"a".repeat(3);      // "aaa"
String.fromCharCode(65);   // "A"
String.fromCodePoint(65);

// قالب:
`${name} سن ${age} دارد`;

// بررسی:
str.localeCompare(other);

مرجع اعداد (Number)

// ثابت‌ها:
Number.MAX_SAFE_INTEGER;  // 2^53 - 1
Number.MIN_SAFE_INTEGER;
Number.MAX_VALUE;
Number.POSITIVE_INFINITY;
Number.NaN;

// تبدیل:
Number("42");       // 42
Number("4.2");      // 4.2
parseInt("42px");   // 42
parseFloat("3.14"); // 3.14
+"42";              // 42

// بررسی:
Number.isInteger(5);
Number.isNaN(NaN);
Number.isFinite(42);
Number.isSafeInteger(2**53);

// قالب‌بندی:
(1234.5678).toFixed(2);      // "1234.57"
(0.85).toPrecision(2);       // "0.85"
(1234567).toLocaleString("fa-IR");

// تجزیه:
Number.parseFloat;
Number.parseInt;

// بی‌نهایت:
1 / 0;              // Infinity
-1 / 0;             // -Infinity

مرجع Math

// ثابت:
Math.PI;
Math.E;

// گرد کردن:
Math.round(4.5);    // 5
Math.floor(4.9);    // 4
Math.ceil(4.1);     // 5
Math.trunc(4.9);    // 4
Math.sign(-5);      // -1

// توان و ریشه:
Math.pow(2, 8);     // 256
Math.sqrt(16);      // 4
Math.cbrt(27);      // 3
Math.hypot(3, 4);   // 5

// لگاریتم:
Math.log(Math.E);   // 1
Math.log2(8);       // 3
Math.log10(100);    // 2
Math.exp(1);        // 2.718...

// مثلثات:
Math.sin(0);
Math.cos(0);
Math.tan(0);
Math.atan2(1, 1);   // زاویه

// کمینه/بیشینه:
Math.min(1, 2, 3);
Math.max(1, 2, 3);

// تصادفی:
Math.random();               // 0 تا < 1
Math.floor(Math.random() * 6) + 1;  // تاس ۱-۶

// قدرمطلق:
Math.abs(-5);       // 5

مرجع Date

// ساخت:
new Date();
new Date(2025, 0, 15);
new Date("2025-01-15");
new Date(1700000000000);
Date.now();

// دریافت:
d.getFullYear();
d.getMonth();        // 0-11!
d.getDate();
d.getDay();          // 0=یکشنبه
d.getHours();
d.getMinutes();
d.getSeconds();

// UTC:
d.getUTCFullYear();
d.getUTCHours();

// تغییر:
d.setFullYear(2026);
d.setMonth(11);
d.setDate(25);

// تبدیل:
d.toISOString();     // "2025-01-15T..."
d.toJSON();
d.toLocaleDateString("fa-IR");
d.toLocaleString("fa-IR", { dateStyle: "full" });
d.getTime();         // timestamp
Date.parse("2025-01-15");

مرجع RegExp

// ساخت:
/pattern/flags;
new RegExp("pattern", "flags");

// Flagها:
// g — global
// i — case-insensitive
// m — multiline
// s — dotAll
// u — unicode
// y — sticky

// کلاس‌ها:
\d  // رقم
\D  // غیر رقم
\w  // حرف/عدم/_
\s  // فاصله
.   // هر چیزی به جز newline

// Quantifierها:
+     // ۱ یا بیشتر
*     // ۰ یا بیشتر
?     // ۰ یا ۱
{n}   // دقیقاً n
{n,}  // حداقل n
{n,m} // بین n و m

// گروه‌ها:
(...)       // capturing
(?<name>...) // named
(?:...)     // non-capturing
\1          // backreference

// جستجو:
regex.test(str);
str.match(regex);
str.matchAll(regex);
regex.exec(str);

// جایگزینی:
str.replace(regex, "new");
str.replaceAll(regex, fn);

مرجع Map و Set

// Map:
const map = new Map();
map.set("key", "value");
map.get("key");
map.has("key");
map.delete("key");
map.size;
map.clear();

for (const [k, v] of map) { }
map.keys();
map.values();
map.entries();

// Set:
const set = new Set([1, 2, 3]);
set.add(4);
set.has(1);
set.delete(1);
set.size;

// تبدیل:
[...set];
[...map.keys()];
Array.from(set);

// WeakMap/WeakSet:
const wm = new WeakMap();
wm.set(obj, "data");  // کلید باید object

مرجع Promise و Async

// ساخت:
new Promise((resolve, reject) => { });
Promise.resolve(5);
Promise.reject(err);

// مصرف:
promise
    .then(result => { })
    .catch(err => { })
    .finally(() => { });

// ترکیب:
Promise.all([p1, p2]);         // همه موفق
Promise.allSettled([p1, p2]);  // همه تمام
Promise.race([p1, p2]);        // اولین
Promise.any([p1, p2]);         // اولین موفق

// Async:
async function fn() {
    const result = await promise;
    return result;
}

// خطا:
try {
    await risky();
} catch (e) { }

// حلقه ناهمگام:
for await (const item of asyncIterable) { }

// AbortController:
const ctrl = new AbortController();
fetch(url, { signal: ctrl.signal });
ctrl.abort();

مرجع JSON

// stringify:
JSON.stringify(obj);
JSON.stringify(obj, null, 2);       // خوانا
JSON.stringify(obj, ["a", "b"]);    // فیلتر
JSON.stringify(obj, replacerFn);

// parse:
JSON.parse(str);
JSON.parse(str, reviverFn);

// مدیریت خطا:
try { JSON.parse(bad); } catch { }

// متد سفارشی:
obj.toJSON = () => ({ safe: "data" });

مرجع DOM

// انتخاب:
document.getElementById("id");
document.querySelector(".css");
document.querySelectorAll(".css");

// ساخت:
const el = document.createElement("div");

// تغییر:
el.textContent = "متن";
el.innerHTML = "<b>HTML</b>";
el.className = "class";
el.id = "id";

// ویژگی‌ها:
el.setAttribute("name", "value");
el.getAttribute("name");
el.hasAttribute("name");
el.removeAttribute("name");
el.dataset.custom;   // data-custom

// کلاس‌ها:
el.classList.add("a");
el.classList.remove("a");
el.classList.toggle("a");
el.classList.contains("a");
el.classList.replace("a", "b");

// اضافه:
parent.appendChild(child);
parent.prepend(child);
parent.append(child1, child2, "text");
el.insertAdjacentHTML("beforeend", html);

// حذف:
el.remove();

// جایگزینی:
el.replaceWith(newEl);
el.replaceChildren(...children);

// پیمایش:
el.parentElement;
el.children;
el.firstElementChild;
el.lastElementChild;
el.previousElementSibling;
el.nextElementSibling;
el.closest(".selector");

// اندازه:
el.getBoundingClientRect();
el.offsetWidth;
el.offsetHeight;
el.scrollHeight;

// محتوا:
el.insertAdjacentText("afterbegin", "text");
document.createDocumentFragment();

مرجع Events

// شنیدن:
el.addEventListener("click", handler);
el.addEventListener("click", handler, { once: true });

// حذف:
el.removeEventListener("click", handler);

// شیء رویداد:
e.type;
e.target;
e.currentTarget;
e.clientX, e.clientY;
e.key;
e.preventDefault();
e.stopPropagation();

// سفارشی:
const event = new CustomEvent("name", { detail: data });
el.dispatchEvent(event);

// delegate:
parent.addEventListener("click", e => {
    const target = e.target.closest(".item");
});

// انواع مهم:
// click, dblclick, mousedown, mouseup
// mouseenter, mouseleave, mousemove
// keydown, keyup, keypress
// input, change, focus, blur, submit
// scroll, resize, load, DOMContentLoaded
// dragstart, dragover, drop
// touchstart, touchmove, touchend

مرجع Fetch و HTTP

// GET:
const res = await fetch(url);
const data = await res.json();

// POST:
await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data)
});

// FormData:
const fd = new FormData(form);
await fetch(url, { method: "POST", body: fd });

// بررسی:
if (!res.ok) throw new Error(res.status);
res.status;     // 200
res.headers;

// خطا:
try { } catch (e) { }
// TypeError — شبکه
// AbortError — لغو

// headers:
const h = new Headers({ "X-Key": "val" });
h.append("X-Key2", "v2");
h.get("X-Key");

// Request:
const req = new Request(url, { method: "GET" });
await fetch(req);

مرجع Web APIs

// Storage:
localStorage.setItem("k", "v");
localStorage.getItem("k");
localStorage.removeItem("k");
sessionStorage.getItem("k");

// URL:
const url = new URL("https://x.com/path?q=1");
url.searchParams.get("q");
url.pathname;

// Timer:
setTimeout(fn, ms);
setInterval(fn, ms);
clearTimeout(id);
clearInterval(id);

// Clipboard:
await navigator.clipboard.writeText("متن");
await navigator.clipboard.readText();

// Notification:
await Notification.requestPermission();
new Notification("عنوان", { body: "متن" });

// Geolocation:
navigator.geolocation.getCurrentPosition(
    pos => pos.coords.latitude
);

// console:
console.log/warn/error/info/table/time/group/trace

مرجع Reflect و Proxy

// Reflect:
Reflect.get(obj, "key");
Reflect.set(obj, "key", val);
Reflect.has(obj, "key");
Reflect.deleteProperty(obj, "key");
Reflect.ownKeys(obj);
Reflect.apply(fn, thisArg, args);
Reflect.construct(Class, args);

// Proxy:
const p = new Proxy(target, {
    get(t, prop) { return t[prop]; },
    set(t, prop, v) { t[prop] = v; return true; },
    has(t, prop) { return prop in t; },
    deleteProperty(t, prop) { delete t[prop]; return true; }
});

مرجع Global Objects

// در همه‌جا:
globalThis;       // ریشه
Infinity;
NaN;
undefined;

// توابع global:
parseInt("42");
parseFloat("3.1");
isNaN(x);
isFinite(x);
encodeURI(url);
decodeURI(url);
encodeURIComponent(part);
decodeURIComponent(part);
eval(str);  // ⚠️ ننویسید!
structuredClone(obj);  // کپی عمیق
queueMicrotask(fn);

مرجع Console

console.log("پیام");
console.error("خطا");
console.warn("هشدار");
console.info("اطلاعات");
console.debug("دیباگ");

console.table(array);            // جدول
console.group("نام");             // گروه
console.groupEnd();
console.groupCollapsed("نام");

console.time("نام");
console.timeEnd("نام");           // زمان

console.trace();                  // stack
console.clear();                  // پاک
console.count("نام");             // شمارش
console.assert(cond, "پیام");    // ادعا

این مبحث بخشی از دوره آموزش کامل جاوا اسکریپت است.

ابزارهای مرتبط