جاوا اسکریپت مدرن و ECMAScript

ECMAScript چیست، تاریخچه ES5 تا ES2025، ویژگی‌های جدید هر نسخه، قابلیت‌های مدرن و مقایسه نسخه‌ها.

ECMAScript چیست؟

ECMAScript (ES) استاندارد رسمی جاوا اسکریپت است که توسط ECMA International تعریف می‌شود:

JavaScript = پیاده‌سازی (Mozilla, Google, ...)
ECMAScript = مشخصات/استاندارد

// ماژول‌های استاندارد:
- ES3 (1999) — پایه
- ES5 (2009) — JSON، strict
- ES6/ES2015 — انقلاب!
- ES2016+ — سالانه

ES5 (2009) — پایه‌های مدرن

"use strict";  // حالت سخت‌گیرانه

// JSON:
JSON.parse('{"a":1}');
JSON.stringify({a: 1});

// متدهای آرایه:
[1,2,3].forEach(x => log(x));
[1,2,3].map(x => x*2);
[1,2,3].filter(x => x>1);
[1,2,3].reduce((a,b) => a+b);

// Property access:
Object.keys(obj);
Object.defineProperty(obj, "key", { value: 1 });

// bind:
fn.bind(thisArg);

ES6 / ES2015 — بزرگ‌ترین به‌روزرسانی

// let و const — بلوکی:
let x = 1;
const PI = 3.14;

// Arrow Functions:
const add = (a, b) => a + b;
const square = x => x * x;

// Template Literals:
const msg = `سلام ${name}!

// Classes:
class Person {
    constructor(name) { this.name = name; }
}

// ماژول‌ها:
import { x } from "./mod.js";
export default class {}

// Promise:
fetch(url).then(r => r.json());

// Destructuring:
const [a, b] = [1, 2];
const { name, age } = user;

// Spread/Rest:
const arr = [...old, newItem];
function f(...args) {}

// Parameters پیش‌فرض:
function greet(name = "مهمان") {}

// Symbol:
const id = Symbol("id");

// Map و Set:
const map = new Map();
const set = new Set();

// Generator:
function* gen() { yield 1; }

// for...of:
for (const item of arr) {}

ES2016 — کوچک اما مفید

// Includes — جایگزین indexOf:
[1, 2, 3].includes(2);      // true
"سلام".includes("لا");       // true

// عملگر توان:
2 ** 10;                     // 1024
// به‌جای Math.pow(2, 10)

ES2017 — Async/Await

// async/await — انقلاب ناهمگام:
async function getData() {
    const res = await fetch(url);
    return res.json();
}

// Object.values و entries:
Object.values({a:1, b:2});   // [1, 2]
Object.entries({a:1, b:2});  // [["a",1], ["b",2]]

// padStart و padEnd:
"5".padStart(3, "0");        // "005"
"5".padEnd(3, "0");          // "500"

// Object.getOwnPropertyDescriptors:
Object.getOwnPropertyDescriptors(obj);

// trailing comma در پارامترها:
function f(a, b,) {}

ES2018 — Async Iterator و Rest

// Async Iteration:
for await (const item of asyncIterable) {}

// Rest/Spread برای اشیا:
const { a, ...rest } = obj;

// Promise.finally:
promise
    .then(handle)
    .catch(err)
    .finally(cleanup);  // همیشه!

// RegExp بهبودها:
// Named groups:
const m = "2025-01".match(/(?<year>\d+)-(?<month>\d+)/);
m.groups.year;  // "2025"

// s flag — dotAll:
/hello.world/s.test("hello\nworld");  // true

// RegExp lookbehind:
/(?<=$)\d+/.exec("$100");  // ["100"]

ES2019 — بهبودهای کوچک

// flat و flatMap:
[1, [2, [3]]].flat();       // [1, 2, [3]]
[1, [2, [3]]].flat(2);      // [1, 2, 3]
[1, 2].flatMap(x => [x, x*2]);  // [1,2,2,4]

// Object.fromEntries:
Object.fromEntries([["a", 1]]);  // {a: 1}

// trimStart و trimEnd:
"  hi  ".trimStart();  // "hi  "
"  hi  ".trimEnd();    // "  hi"

// Optional catch binding:
try { risky(); } catch { /* بدون (e) */ }

// Symbol.description:
Symbol("foo").description;  // "foo"

// stable sort — مرتب‌سازی پایدار:
[...arr].sort();

ES2020 — قدرتمند

// Optional Chaining:
user?.address?.city;
fn?.();

// Nullish Coalescing:
const port = input ?? 3000;  // فقط null/undefined

// BigInt — اعداد بزرگ:
const big = 9007199254740993n;
big + 1n;

// Promise.allSettled:
Promise.allSettled([p1, p2]).then(results => {
    results[0].status;  // "fulfilled"
});

// globalThis — همه‌جا:
globalThis.console;  // مرورگر و Node

// Dynamic import:
const module = await import("./heavy.js");

// String.matchAll:
for (const m of "a1b2".matchAll(/\w/g)) {}

// Module Metadata:
import.meta.url;

ES2021 — بهبودهای عملی

// Logical Assignment:
x ||= defaultValue;   // اگر falsy
x &&= backup;         // اگر truthy
x ??= fallback;       // اگر null/undefined

// Numeric Separators:
1_000_000_000;        // خواناتر!
0xFF_FF_FF;

// String.replaceAll:
"a-b-c".replaceAll("-", "+");  // "a+b+c"

// Promise.any:
Promise.any([p1, p2]).then(first => {});

// WeakRef:
const ref = new WeakRef(obj);
ref.deref()?.method();

ES2022 — کلاس‌های مدرن

// Class Fields:
class Counter {
    count = 0;              // عمومی
    #secret = "خصوصی";      // خصوصی!
    static total = 0;       // ایستا
    static #hidden = 0;     // ایستا خصوصی

    static {                 // Static Block
        console.log("init");
    }

    #privateMethod() {}      // متد خصوصی

    increment() { return ++this.count; }
}

// at — ایندکس منفی:
[1,2,3].at(-1);       // 3 — آخرین!
"abc".at(-2);         // "b"

// Object.hasOwn:
Object.hasOwn(obj, "key");  // امن‌تر از hasOwnProperty

// Error Cause:
throw new Error("پیام", { cause: originalError });

// top-level await:
const config = await loadConfig();

ES2023 — آرایه‌های تغییرناپذیر

// toSorted — sort بدون تغییر:
const sorted = arr.toSorted();  // جدید برمی‌گرداند

// toReversed:
const reversed = arr.toReversed();

// toSpliced:
const spliced = arr.toSpliced(1, 2);

// with — جایگزینی:
const updated = arr.with(0, "new");

// findLast و findLastIndex:
arr.findLast(x => x > 5);
arr.findLastIndex(x => x > 5);

// Hashbang:
#!/usr/bin/env node

ES2024 — جدیدترین

// Object.groupBy:
const grouped = Object.groupBy(users, u => u.role);
// { admin: [...], user: [...] }

// Map.groupBy:
const byDept = Map.groupBy(employees, e => e.dept);

// Promise.withResolvers:
const { promise, resolve, reject } = Promise.withResolvers();

// String isWellFormed:
str.isWellFormed();       // UTF-16 معتبر؟
str.toWellFormed();       // اصلاح

// RegExp v flag — پیشرفته:
/[\p{Script=Arabic}]/v.test("س");  // true

// Atomics.waitAsync — بدون بلاک

ES2025 — آینده نزدیک

// Iterator Helpers — پیشنهاد فعال:
// iterator.map(x => x*2).filter(...).take(5)

// Temporal — تاریخ مدرن:
// Temporal.Now.instant();
// Temporal.PlainDate.from("2025-01-15");

// Explicit Resource Management:
// await using resource = open();  — خودکار بسته می‌شود

// Import Attributes:
// import data from "./data.json" with { type: "json" };

مقایسه نسخه‌ها

نسخهسالسردسته‌ها
ES52009JSON، strict، متدهای آرایه
ES62015class، let/const، Promise، ماژول
ES2017async/await
ES2020?., ??، BigInt
ES2022#private، at، top-await
ES2024groupBy، withResolvers

پشتیبانی مرورگرها

// بررسی پشتیبانی:
// caniuse.com
// kangax.github.io/compat-table

// قاعده سرانگشتی:
// - ES6: همه مرورگرهای مدرن ✓
// - ES2022: Chrome 94+, Firefox 93+
// - ES2024: Chrome 117+

// برای سازگاری — Babel/Polyfill:
// import "core-js/stable";

نکات مدرن‌نویسی

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

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