What is JavaScript?
Definition · History · ECMAScript Versions · What JS Can Do
JavaScript هي لغة برمجة بتشتغل جوا الـ browser — يعني عند الـ client مش على الـ server. لو الـ HTML هو "العظام"، والـ CSS هو "الملابس"، فالـ JavaScript هو "الحركة والتفاعل"!
JavaScript ليها علاقة بـ Java؟ ❌ لأ!
اتعملت 1995 في Netscape واسمها الأصلي كان "LiveScript" — Java لغة تانية خالص!
Interpreter مدمج جوا الـ browser بيشغّلها. مش محتاج compilation زي Java أو C++.
Client-side: بتشتغل عند المستخدم بعد ما الـ browser استلم الـ HTML
Server-side: ممكن برضو بـ Node.js
<html>
<body>
<script>
// بيكتب على الصفحة مباشرة
document.write("Hello World!");
// بيكتب في الـ console
console.log("Hello Dev!");
// Popup
window.alert("مرحبا يا عالم!");
</script>
</body>
</html>
بتعدل في الـ HTML بعد ما الصفحة اتحملت — تضيف/تمسح/تغير elements
بتتفاعل مع الكليك، الـ hover، الـ submit، الـ scroll
بتتحقق من الـ forms قبل ما يتبعتوا للـ server
بتعمل وتقرأ cookies عشان تحفظ بيانات المستخدم
بتجيب بيانات من الـ server من غير ما تـreload الصفحة!
لغة برمجة كاملة — variables, functions, classes, OOP
| Version | Year | أهم Features |
|---|---|---|
| ES3 | 1999 | Regular Expressions, try/catch |
| ES5 | 2009 | "use strict", JSON, forEach, map, filter, reduce |
| ES6 / ES2015 | 2015 | let/const, Arrow functions, Classes, Promises, Modules — الأهم! |
| ES7–ES14 | 2016–2023 | async/await, flat, findIndex, الكثير |
Adding JavaScript to HTML
Internal · External · Placement · console.log · window.alert
<head>
<script>
function greet() {
alert("Hi!");
}
</script>
</head>
بيتحمل قبل الـ body — مناسب للـ functions
<body>
<script>
document.write(
"Hello!"
);
</script>
</body>
بيشتغل وهو الـ page بيتحمل
<script
src="myscript.js"
></script>
/* في myscript.js: */
/* JS code فقط — بدون HTML! */
الأفضل — ملف منفصل
• External JS file →
<script src="file.js"></script> مش href ولا link!• مش
<import src="file.js"> ولا <script link="file.js">• External JS file = مش المفروض يحتوي على HTML tags!
// Console — للـ developers فقط
console.log("Check this!"); ← final-2024 Q11
// Alert Box — popup للمستخدم
window.alert("Hello!"); ← final-2024 Q12
// Confirm Box — Yes/No
window.confirm("Are you sure?");
// Prompt — input from user
window.prompt("Your name?", "Ahmed");
// Write to HTML page
document.write("Hello World!");
document.writeln("With newline");
console.log() → بيكتب في الـ browser console
window.alert() → بيعمل popup box
console.write() ❌ — مش موجود!console.output() ❌ — مش موجود!window.alertHTML() ❌ — مش موجود!window.alertBox() ❌ — مش موجود!بتحدد أو بتقرأ محتوى الـ HTML element.
document.getElementById("demo").innerHTML = "New text";innerHTML vs innerText: innerHTML بيفسر HTML tags، innerText بيعاملها كـ text عادي.
Quiz — JS Foundations
أسئلة من final-2024 و final-2025
Variables & Data Types
var · let · const · typeof · Type Conversion
// var — function-scoped (قديم)
var x = 10;
var x = 20; // OK — ممكن تعيد التعريف
x = 30; // OK — ممكن تعدّل
// let — block-scoped (ES6 ✅)
let y = 10;
// let y = 20; ❌ لا يمكن إعادة التعريف
y = 20; // OK — ممكن تعدّل
// const — block-scoped, read-only (ES6 ✅)
const PI = 3.14;
// PI = 3.15; ❌ TypeError — لا يمكن التغيير!
// const PI; ❌ لازم تعطيها قيمة وقت التعريف!
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Re-declare | ✅ نعم | ❌ لا | ❌ لا |
| Re-assign | ✅ نعم | ✅ نعم | ❌ لا |
| Hoisting | Yes (undefined) | Yes (TDZ) | Yes (TDZ) |
const VALUE = 10; VALUE = 20; → يعطي TypeError لأن const لا يمكن إعادة تعيينه. مش ValueError!var X = 10; // global variable
function myfunc() {
let x = 20; // مختلف! lowercase 'x' وlet
}
document.write(X); // ⚡ Output: 10
// ليه؟ لأن:
// 1. document.write بيقرأ X الـ global مش x الـ local
// 2. X (uppercase) ≠ x (lowercase) — case-sensitive!
// 3. الـ function مش اتنفذت حتى لو تعرفت
typeof(12.34) → "number" (مش "float" ولا "int"!)typeof([1,2,3]) → "object" (arrays هي objects!)typeof(null) → "object" (معروف كـ JavaScript bug!)typeof(undefined) → "undefined"var x = 12.34;
typeof(x); → "number"
var arr = [1,2,3];
typeof(arr); → "object"
function f() {}
typeof(f); → "function"
var a;
typeof(a); → "undefined"
الـ + مع strings بيعمل concatenation. باقي الـ operators بيحوّل الـ string لـ number.
// + مع string = concatenation (من اليسار للليمين)
10 + 20 + "5" → "305" ← final-2024 Q18
// ليه؟ 10+20=30 أولاً (numbers), ثم 30+"5"="305"
100 - 20 + "5" → "805" ← mid-2023 Q44
// ليه؟ 100-20=80 (arithmetic), ثم 80+"5"="805"
"20" + 10 → "2010" ← final-2024 Q60
"20" - 10 → 10 ← الـ - بيحوّل string لـ number!
"37" - 7 → 30 ← numeric subtraction
"37" + 7 → "377" ← string concatenation!
لو أي operand string + الـ operator هو
+ → string concatenation من وقت ما لقى الـ stringلكن لو الـ operator هو
- أو * أو / → يحوّل الـ string لـ number!False: null, undefined, 0, "" (empty string), false
True: كل حاجة تانية — حتى "0" وarray فاضي []!
Scope & "use strict"
Global Variables · Block Scope · Strict Mode
// بدون strict mode:
x = 10; // Works! (global variable)
// مع strict mode:
"use strict";
x = 10; // ❌ ERROR! x is not declared
// الصح:
"use strict";
let x = 10; // ✅
// ملاحظة: strict mode بيمنع:
// - استخدام variables بدون تعريف
// - حذف variables بـ delete
// - استخدام reserved words كـ variable names
بتحوّل JS لـ "strict mode" اللي بيمنع الـ bad practices:
• لا يسمح بـ undeclared variables
• بيعطي errors بدل ما يتجاهل الأخطاء
• بيحسّن الـ performance
• بيجهّز الكود لـ future JS versions
'use strict' does: Enforces stricter parsing and error-handling rules
In strict mode: x = 10; → Error: x is not defined
(مش بيعطي 10 ولا undefined!)
var a = 10; // property of window (var)
b = 20; // implicit global (no var/let/const)
console.log(window.a); // 10
console.log(window.b); // 20
delete a; // false — var variables can't be deleted
delete b; // true — implicit globals CAN be deleted
console.log(a); // 10 (still exists)
console.log(b); // ReferenceError! (was deleted)
// عدد طرق تعريف الـ variable:
var x = 1; // 1
let y = 2; // 2
const z = 3; // 3 ← إجمالي: 3 طرق!
Quiz — Variables & Scope
أسئلة من final-2024 و final-2025
Functions & Arrow Functions
Declaration · Expression · Default Params · Arrow Syntax
// 1. Function Declaration — التقليدي
function add(a, b) {
return a + b;
}
// 2. Function Expression — بتخزنها في variable
const add = function(a, b) {
return a + b;
};
// 3. Arrow Function (ES6) — الأقصر والأجمل!
const add = (a, b) => a + b;
// لو statement واحدة: مش محتاج {} ولا return!
// Default Parameters (ES6)
function greet(name = "Guest") {
return "Hello " + name;
}
greet(); → "Hello Guest"
greet("Ahmed"); → "Hello Ahmed"
const f = (a, b) => a + b + 5;
f(4, 5) = 4 + 5 + 5 = 14 ✅
f(3, 4) = 3 + 4 + 5 = 12
// Arrow syntax مختلفة:
const sq = x => x * x; // parameter واحد — بدون ()
const hi = () => "Hello"; // بدون params
const sum = (a,b) => { // multi-line: لازم {} وreturn
let result = a + b;
return result;
};
// map/filter مع Arrow — من الامتحانات!
myNumbers.map((value) => value * 4);
myNumbers.filter((value) => value < 10);
const f = (a,b) => a+b+5;f(4,5) = 4+5+5 = 14مش 9 (4+5) ومش 14 أو أي حاجة تانية!
Multiply by 4:
myNumbers.map((value)=>value*4) ✅myNumbers.map(value*4) ❌ — لازم function!Filter less than 10:
myNumbers.filter((value)=>value<10) ✅myNumbers.map(...) ❌ — map مش filter!eval · Rest Parameter · Spread Operator
eval() · ...rest · ...spread · arguments
// Q30 — final-2024
let x = 10;
let y = 20;
let text = "x * y";
let result = eval(text);
// eval("x * y") = x * y = 10 * 20 = 200
document.getElementById("demo").innerHTML = result;
// Output: 200 ✅
// Q47 — mid-2023
let x = 10, y = 20;
let text = "y-x";
let result = eval(text); = y-x = 20-10 = 10
document.write(result); // Output: 10
// Q78 — final-2025 (الصعبة!)
var writeMe = "console.log('document.writeln(x);')"
var x = 13
eval(writeMe);
// eval runs: console.log('document.writeln(x);')
// → prints the STRING "document.writeln(x);" in console
// NOT x's value! Because x is inside single quotes
Security risk — بيشغّل أي code!
Performance problem — JS engine مش قادر يـoptimize.
writeMe = "console.log('document.writeln(x);')"eval بيشغّل:
console.log('document.writeln(x);')النتيجة: بيكتب الـ string "document.writeln(x);" في الـ console — مش قيمة x!
لأن 'document.writeln(x);' هو نص داخل single quotes.
// ...args يجمع كل الـ arguments في array
function test(...args) {
document.write(typeof(args)); → "object"
// ليه object؟ لأن arrays هم objects!
}
test(12); // args = [12]
// Sum example from slides:
function sum(...args) {
let total = 0;
for (let arg of args) total += arg;
return total;
}
sum(1, 2, 3, 4, 5); → 15
// Multiply example from final-2025:
function multiply(...myNumbers) {
let total = 1;
for (let n of myNumbers) total *= n;
return total;
}
الـ
... في الـ function parameters:→ Rest Parameter → يجمع arguments في array
typeof(args) = "object"
لأن arrays في JS هم objects!
The "..." will:
→ Allow the function to change the arguments to an array ✅
مش "waiting for more arguments" ولا "distributing to separate numbers".
Quiz — Functions & eval
أسئلة من final-2024 · mid-2023 · final-2025
Arrays & ES5 Array Methods
forEach · map · filter · reduce · find · indexOf · concat · flat
| Method | بيعمل إيه؟ | بيرجع إيه؟ | مثال |
|---|---|---|---|
forEach(fn) | بيلف على كل element | undefined | arr.forEach(v => console.log(v)) |
map(fn) | بيحوّل كل element | Array جديد | [1,2,3].map(v=>v*2) → [2,4,6] |
filter(fn) | بيصفّي العناصر | Array جديد | [1,2,3].filter(v=>v>1) → [2,3] |
reduce(fn, init) | بيجمع لـ قيمة واحدة | Single value | [1,2,3].reduce((t,v)=>t+v, 0) → 6 |
find(fn) | أول element يطابق | Element أو undefined | [10,20,30].find(v=>v>10) → 20 |
some(fn) | لو أي element يطابق | boolean | [1,2,3].some(v=>v>2) → true |
every(fn) | لو كل elements تطابق | boolean | [1,2,3].every(v=>v>0) → true |
indexOf(v) | أول index لـ قيمة | number (-1 لو مش موجود) | [10,20,10].indexOf(10) → 0 |
lastIndexOf(v) | آخر index لـ قيمة | number (-1 لو مش موجود) | [10,20,10].lastIndexOf(10) → 2 |
concat(arr) | يدمج arrays | Array جديد | [1,2].concat(3,4) → [1,2,3,4] |
flat(depth) | بيفرد nested arrays | Array جديد | [[1,2],[3]].flat() → [1,2,3] |
pop() | يشيل آخر element | الـ element اللي اتشال | [1,2,3].pop() → 3 |
// reduce(callback, initialValue)
// callback(accumulator, currentValue)
// Q21 final-2024: initial = 2
var numbers = [1,2,3,4];
function myfunc(total, value) { return total + value; }
var sum = numbers.reduce(myfunc, 2);
// Start: total=2 (initial), value=1 → 3
// Next: total=3, value=2 → 5
// Next: total=5, value=3 → 8
// End: total=8, value=4 → 12 ✅
// Q22 final-2024: no initial value, subtraction
var numbers = [170, 50, 25];
function myfunc(total, value) { return total - value; }
var sum = numbers.reduce(myfunc);
// Start: total=170 (first element!), value=50 → 120
// End: total=120, value=25 → 95 ✅
// Q45 mid-2023: initial = 3
var numbers = [1,2,3,4];
var sum = numbers.reduce(myfunc, 3);
// 3+1+2+3+4 = 13 → None of previous (d)!
• لو في initial value → تبدأ الـ accumulator بـ الـ initial value
• لو مفيش initial value → الـ accumulator يبدأ بـ أول element والـ loop تبدأ من الـ second
var numbers = [10, 20, 30];
function myFunction(value) { return value > 10; }
// find() → أول element يطابق فقط
numbers.find(myFunction); → 20 (not [20,30]!) ← Q28 final-2024
// filter() → كل elements تطابق
numbers.filter(myFunction); → [20, 30] (array!)
typeof(numbers.filter(myFunction)) → "object" ← Q31 final-2024
// some() → يرجع boolean
numbers.some(myFunction); → true (boolean, not array!)
typeof(numbers.some(myFunction)) → "boolean" ← Q49 mid-2023
// map() مع boolean function (Q46 mid-2023):
[45,4,9,16,25].map(v => v > 18)
→ [true, false, false, false, true] ← مش [45,25]!
// indexOf vs lastIndexOf — Q32 final-2024
var numbers = [10, 20, 10, 30];
// 0 1 2 3
var y = numbers.lastIndexOf(10); → 2 (last occurrence)
var z = numbers.indexOf(30); → 3
document.write(y + z); → 5 ✅
// concat — Q34 final-2024
var quiz = [1, 2, 3];
var result = quiz.concat(6, 7, 8);
document.write(result); → 1,2,3,6,7,8 ✅
// pop() — Q68/Q69 final-2024
var myNumbers = [1, 2, 3];
var x = myNumbers.pop(); → x = 3 (LAST element removed!)
// myNumbers is now [1, 2]
// flat() — Q78 final-2024
const myArr = [1, 2, [3, [4, 5, 6], 7], 8];
const newArr = myArr.flat(); // depth=1 by default
→ [1, 2, 3, [4, 5, 6], 7, 8] → written: 1,2,3,4,5,6,7,8
// flat(2) — Q79 final-2025
const myArr = [1, 2, [3, [4, 5, 6, 7], 8]];
myArr.flat(2); → [1, 2, 3, 4, 5, 6, 7, 8] ✅
// {1:"red"} is NOT an array! Q67 final-2024
var colors = {1:"red", 2:"green"}; ← Object, not Array!
// Array uses []. Object uses {}.
Quiz — Arrays & Methods
أكتر جزء في الامتحانات — تمرن عليه كويس!
Objects & Operators
Object Literals · Property Access · delete · typeof · in
// Object literal
var car = {
color: "red",
weight: 2000,
mfr: "Hyundai"
};
// 3 طرق للوصول للـ properties:
car.color; → "red" ✅ dot notation
car["color"]; → "red" ✅ bracket + string
var p = "color";
car[p]; → "red" ✅ bracket + variable
car[color]; → ❌ ERROR! color not defined
// Properties are called... "Properties"!
// (Q52 mid-2023) Name وTelephonenumber = Properties
// delete operator:
delete car.color;
car.color; → undefined (not deleted from JS, just undefined)
// in operator:
"weight" in car; → true
"color" in car; → false (was deleted)
const cars = { company:"Honda", color:"white" };var x = "color";delete cars.company;document.write(cars.company); → "undefined"document.write(cars[x]); → "white"Combined: "undefinedwhite" ✅
JSON.stringify(obj) → Object to StringJSON.parse(str) → String to Objectstringify = to send to server
parse = to use received data
ES6 Classes & OOP
class · constructor · extends · super · prototype · Getters
// Class Definition
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
// Getter - final-2025 Q44
get carName() {
return this.name;
}
}
let myCar1 = new Car("Ford", 2014);
// Inheritance (extends & super)
class Model extends Car {
constructor(name, year, model) {
super(name, year); // ⚡ Calls parent's constructor!
this.model = model;
}
}
// Constructor: function to initialize properties
// super(): calls the parent constructor
// Constructor function (ES5 OOP)
function Cell(r, c) {
this.row = r;
this.col = c;
}
// Adding property using prototype
Cell.prototype.width = 20;
var c1 = new Cell(0, 0);
document.write(c1.width); → 20
// instanceof checks if object is of a specific class
if (c1 instanceof Cell) {
// true!
}
بتسمحلك تضيف properties و methods لـ Object Constructors اللي موجودة قبل كدة.
Cell.prototype.width = 20; بيخلي كل الـ objects من نوع Cell يمتلكوا width!بيختبر إذا كان الـ object اتعمل من constructor معين.
c1 instanceof Cell ➜ trueQuiz — Objects & Classes
أسئلة الامتحانات (final-2024 & final-2025)
super() عشان نشغل constructor الـ parent.delete بتمسح الـ property دي نهائياً من الـ object.. علشان كده بيتبقى `b: 2` بس.var و let و const.DOM Manipulation
document · Elements · NodeList · Navigation
الـ Document Object Model (DOM) هو هيكل تفريعي أو شجرة بيوصف فيها الـ HTML كـ objects (أو Nodes). ده بيتيح للـ JS إنه يتفاعل مع الـ HTML بسهولة.
• Element Node: زي
<p> و <h1>. (nodeType = 1)• Text Node: النص نفسه. (nodeType = 3)
• Document Node: الـ document كله.
• Attribute: الخصائص للـ elements.
element.firstChild.nodeValue بيجيب النص اللي جوه أي عنصر.في الـ HTML DOM، الـ
nodeName والـ nodeType هما خصائص read-only، مقدرش أغيرهم! (امتحان 2024 Q13)// 1. By ID (بيرجع Single Element)
document.getElementById("demo");
// 2. By Tag Name (بيرجع Collection of elements)
var p_list = document.getElementsByTagName("p");
var count = p_list.length; // عدد البرجرافات
// 3. By Class Name
document.getElementsByClassName("center");
// 4. By CSS Selectors
// querySelector: بيرجع أول عنصر بس!
// querySelectorAll: بيرجع NodeList (لكل العناصر اللي بتطابق)
var nodes = document.querySelectorAll("div > p"); ← Q49 final-2025
// childNodes بترجع كل الـ nodes (text و comments والمسافات!)
var n = myElement.childNodes;
// children بترجع الـ Element nodes بس!
var x = document.body.children; // Collection of elements
var y = x[0].children; // Element nodes only
var z = y[0].firstChild.nodeValue; // النص اللي جواه
// Removing element:
element.remove(); // Q52 final-2025
// Browser Window/History
window.location.href; // بيدينا الـ URL بتاع الصفحة الحالية
window.history.back(); // بيرجعنا للصفحة اللي كانت قبلها في الـ history
children: بيرجع Collection of elements.childNodes: بيرجع Elements, texts, comments.لو العناصر كانت
<li><p>List 1</p></li>:firstLi.children → Element nodes only (اللي هو <p>)!P.firstChild.nodeValue → بيطلع النص "List 1".Quiz — DOM Manipulation
كل أسئلة الامتحانات المرتبطة بـ DOM
Wel.come
p1
p2
p3
p4
p5
p6
. If we wrote "var x=document.getElementsByTagName('p')" inside a script tag, then the length of x will be:Welcome to my page
)JSON, Promises, Async
JSON.parse · JSON.stringify · Promise · async / await
| Method | بتعمل إيه؟ | امتى نستخدمها؟ |
|---|---|---|
JSON.stringify(obj) | Object ➔ String | تحول الأوبجكت بتاعنا لنص عشان نرفعه للموقع (السيرفر). |
JSON.parse(str) | String ➔ Object | تترجم البيانات اللي راجعة من الموقع عشان نعرف نقرأها. |
"Which function is used to serialize an object into a JSON string in JavaScript?"
الإجابة: stringify() ✅
بما إن لغة الـ JS سريعة ومش بتسحب حاجات بطيئة تعطلها، عشان ننفذ حاجات بتطول زي جلب معلومات من الإنترنت، بنلجأ استخدام وعود الـ Promise.
In progress...
.then()
.catch()
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('done!'), 1000);
});
// الكلمة دي هتجبر الكود إنه يوقف انتظار للوعد ده أنه يتحقق!
let result = await promise;
console.log(result); // Output: done! (بعد مرور 1 ثانية)
}
f();
AJAX & Fetch API
XMLHttpRequest · Fetch · Asynchronous Server Calls
كلمة AJAX اختصارا لـ Asynchronous JavaScript And XML. ودي الطريقة اللي بندمج بيها اتصالنا بقاعدة البيانات من غير ما نضطر إننا نعمل Reload أو نحدث الـ Page (تحديث جزء بيتم بس!) (امتحان 2025 Q31)
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// 4 يعني الطلب خلص وكل حاجة تمام!
// 200 يعني الـ Status طالعة Successful
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
// true معناها ان الطلب Asynchronous (بيتم في الخلفية)
xhttp.open("GET", "data.txt", true);
xhttp.send();
}
// تقنية Fetch أحدث وأسهل بكتير لأنها بتعتمد على استخدام الـ Promises!
fetch("data.txt")
.then(response => response.text())
.then(text_data => {
document.getElementById("demo").innerHTML = text_data;
});
Quiz — Modern JS & AJAX
Exam Cheat Sheet
Quick Reference for Final Revision
⚡ Type Coercion rules
"20"+10 ➔ "2010"
10+20+"5" ➔ "305"
"37"-7 ➔ 30
"10" * 2 ➔ 20
🚀 Important typeofs
🔥 Scope & strict
let/const = block scope
🔍 Array Methods Returns
With init: starts at init.