Ecmascript ES6 دليل شامل لـ JavaScript الحديثة
تم التحديث: ٢٧ مارس ٢٠٢٦
ملخص
أحدثت ECMAScript 6 (ES2015) ثورة في JavaScript من خلال الفئات (classes)، والدوال السهمية (arrow functions)، والـ Promises؛ بينما تضيف JavaScript الحديثة (ES2024-2025) خاصية top-level await، وتجميع المصفوفات (Array grouping)، وطرق Set الجديدة، وتحسينات تجعل الكود غير المتزامن (async) أكثر نظافة وتعبيرًا من أي وقت مضى.
تطورت JavaScript بشكل كبير منذ وصول ES6 في عام 2015. ما بدأ كتحسينات كتابية أساسية (syntactic sugar) — مثل الدوال السهمية، وتفكيك البنية (destructuring) ، والقوالب النصية (template literals) — نما ليصبح لغة متطورة وناضجة. بحلول عام 2026، أصبح لدى مطوري JavaScript إمكانية الوصول إلى تجريدات قوية: async/await، والربط الاختياري (optional chaining)، والدمج الصفري (nullish coalescing)، ومكتبة قياسية قوية. إذا تعلمت JavaScript قبل عام 2015، فقد تبدو لغة JS الحديثة وكأنها لغة مختلفة تمامًا. يغطي هذا الدليل الميزات الأساسية من ES6 حتى ES2025 التي يجب على كل مطور معرفتها.
ميزات ES6 الأساسية
الدوال السهمية وصيغة الدوال
جلبت الدوال السهمية (=>) صيغة مختصرة وربطًا سياقيًا لـ this — وهو أحد أكثر التغييرات تأثيرًا في ES6.
// Traditional function
function greet(name) {
return `Hello, ${name}`;
}
// Arrow function (concise)
const greet = (name) => `Hello, ${name}`;
// Multi-line arrow function
const calculate = (a, b) => {
const sum = a + b;
return sum * 2;
};
// Lexical 'this' binding
const button = {
label: 'Click me',
attach() {
document.addEventListener('click', () => {
console.log(this.label); // 'Click me' — this is bound to button
});
}
};
تفكيك البنية (Destructuring Assignment)
يسمح لك تفكيك البنية باستخراج القيم من المصفوفات والكائنات مباشرة إلى متغيرات — مما يوفر الوقت عند التعامل مع معاملات الدوال وهياكل البيانات المعقدة.
// Array destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first, second, rest); // 1 2 [3, 4, 5]
// Object destructuring
const { name, age, city = 'Unknown' } = {
name: 'Alice',
age: 30
};
console.log(name, age, city); // Alice 30 Unknown
// Nested destructuring
const response = {
status: 200,
data: { user: { id: 1, email: 'user@example.com' } }
};
const { data: { user: { email } } } = response;
console.log(email); // user@example.com
// Function parameter destructuring
const displayUser = ({ name, age }) => {
console.log(`${name} is ${age} years old`);
};
displayUser({ name: 'Bob', age: 25 });
الفئات والوراثة (Classes and Inheritance)
توفر فئات ES6 صيغة مألوفة للبرمجة كائنية التوجه، على الرغم من أنها مجرد "تحسين كتابي" فوق نموذج JavaScript القائم على النماذج الأولية (prototypes).
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound`);
}
static info() {
return 'This is an animal class';
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
speak() {
console.log(`${this.name} barks`);
}
}
const dog = new Dog('Max', 'Labrador');
dog.speak(); // Max barks
console.log(Animal.info()); // This is an animal class
الوحدات (استيراد/تصدير)
أحدثت وحدات ES6 ثورة في تنظيم الكود. كل ملف هو وحدة ذات نطاق (scope) خاص بها.
// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
export default class Calculator {
multiply(a, b) { return a * b; }
}
// app.js
import Calculator, { add, subtract } from './math.js';
import * as math from './math.js';
console.log(add(5, 3)); // 8
const calc = new Calculator();
console.log(calc.multiply(4, 5)); // 20
الأنماط غير المتزامنة: الـ Promises وما بعدها
الـ Promises
استبدلت الـ Promises "جحيم ردود النداء" (callback hell) بعمليات غير متزامنة قابلة للتسلسل.
const fetchUser = (id) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) {
resolve({ id, name: 'Alice' );
} else {
reject(new Error('Invalid ID'));
}
}, 100);
});
};
fetchUser(1)
.then(user => console.log(user.name)) // Alice
.catch(err => console.error(err.message));
async/await (ES2017)
تجعل async/await الكود غير المتزامن يُقرأ مثل الكود المتزامن، مما يحسن قابلية القراءة بشكل كبير.
const getUser = async (id) => {
try {
const response = await fetch(`/API/users/${id}`);
const user = await response.json();
return user;
} catch (error) {
console.error('Failed to fetch user:', error);
}
};
// Using async/await
const user = await getUser(1);
console.log(user.name);
// Parallel operations with Promise.all
const [user, posts, comments] = await Promise.all([
fetchUser(1),
fetchPosts(1),
fetchComments(1)
]);
Promise.withResolvers() (ES2024)
أضافت ES2024 خاصية Promise.withResolvers()، مما يوفر طريقة أنظف لإنشاء Promises قابلة للحل خارج المُنشئ (constructor).
// Traditional approach
let resolve, reject;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
// Modern approach (ES2024)
const { promise: p, resolve: r, reject: rej = Promise.withResolvers();
// Practical use case: manual control flow
const { promise, resolve = Promise.withResolvers();
setTimeout(() => resolve('Done!'), 1000);
console.log(await promise); // Done!
الميزات الحديثة (ES2018+)
الربط الاختياري والدمج الصفري (ES2020)
التنقل الآمن عبر الخصائص المتداخلة دون الحاجة إلى فحوصات null متكررة.
const user = { profile: { name: 'Alice' ;
// Optional chaining
console.log(user?.profile?.name); // Alice
console.log(user?.address?.street); // undefined (no error)
// Nullish coalescing - use default only if value is null/undefined
const timeout = config?.timeout ?? 5000; // 5000 if config is null/undefined
const count = 0 ?? 10; // 0 (because 0 is not null/undefined)
Top-Level Await (ES2022)
يمكن لملفات الوحدات الحديثة الآن استخدام await في المستوى الأعلى دون تغليفها في دالة async.
// module.js
const response = await fetch('/API/config');
const config = await response.json();
export default config;
// app.js
import config from './module.js';
console.log(config.apiUrl); // Works seamlessly
تجميع المصفوفات (ES2024)
تقوم Array.groupBy() بتجميع عناصر المصفوفة بواسطة دالة مفتاح، لتحل محل أنماط reduce المطولة.
const users = [
{ id: 1, role: 'admin', name: 'Alice' ,
{ id: 2, role: 'user', name: 'Bob' ,
{ id: 3, role: 'admin', name: 'Charlie' ];
// ES2024 Array.groupBy (for arrays only)
const grouped = Array.groupBy(users, user => user.role);
// { admin: [...], user: [...] }
// Object.groupBy (for iterables)
const byRole = Object.groupBy(users, user => user.role);
console.log(byRole.admin); // Alice and Charlie
طرق Set (ES2024)
اكتسبت الـ Sets طرقًا جديدة لعمليات الاتحاد (union)، والتقاطع (intersection)، والفرق (difference).
const setA = new Set([1, 2, 3]);
const setB = new Set([2, 3, 4]);
// Union
const union = setA.union(setB); // Set(4) { 1, 2, 3, 4 }
// Intersection
const intersection = setA.intersection(setB); // Set(2) { 2, 3 }
// Difference
const difference = setA.difference(setB); // Set(1) { 1 }
// Subset / superset checks
console.log(setA.isSubsetOf(new Set([1, 2, 3, 4]))); // true
console.log(setA.isSupersetOf(new Set([1, 2]))); // true
TypeScript: طريقة JavaScript الحديثة
// TypeScript adds type annotations
interface User {
id: number;
name: string;
email: string;
}
const fetchUser = async (id: number): Promise<User> => {
const response = await fetch(`/API/users/${id}`);
return response.json();
};
// Type checking prevents errors at compile time
const user = await fetchUser(1);
console.log(user.name); // ✓ type-safe
console.log(user.nonexistent); // ✗ compile error
المولدات والمكررات (Generators and Iterables)
توفر المولدات طريقة لتعريف تسلسلات قابلة للتكرار باستخدام function* و yield.
function* countdown(n) {
while (n > 0) {
yield n;
n--;
}
}
for (const num of countdown(3)) {
console.log(num); // 3, 2, 1
}
// Manual iteration
const gen = countdown(3);
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: undefined, done: true }
أنماط عملية لعام 2026
معالجة الأخطاء باستخدام async/await
const robustFetch = async (url, retries = 3) => {
for (let attempt = 0; attempt < retries; attempt++) {
try {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (error) {
if (attempt === retries - 1) تابع التعلم
مقالات ذات صلة
ابقَ على مسار النيرد
بريد واحد أسبوعياً — دورات، مقالات معمّقة، أدوات، وتجارب ذكاء اصطناعي.
بدون إزعاج. إلغاء الاشتراك في أي وقت.