32. سير التحكم: عبارة if
يشير سير التحكم (Control Flow) إلى الترتيب الذي يتم به تنفيذ العبارات الفردية أو التعليمات أو استدعاءات الدوال. الأداة الأساسية لسير التحكم هي عبارة if، التي تسمح بتشغيل الكود فقط إذا كان الشرط صحيحًا.
الصيغة
javascript if (condition) { // Code inside the curly braces runs ONLY if the condition is true (يتم تشغيل الكود داخل الأقواس المعقوفة فقط إذا كان الشرط صحيحًا) }
// Code outside the braces runs regardless of the condition (يتم تشغيل الكود خارج الأقواس بغض النظر عن الشرط)
مثال
javascript let temperature = 35;
if (temperature > 30) { console.log('It is extremely hot outside!'); }
console.log('Finished checking temperature.');
// Output: // It is extremely hot outside! // Finished checking temperature.
الصدقية (Truthiness) في if
تذكر أن JS تستخدم قيم الصدقية/الزائفة لفحص الشرط.
javascript let userName = 'Charlie'; // A non-empty string is Truthy (سلسلة نصية غير فارغة هي صادقة)
if (userName) {
console.log(Hello, ${userName}.);
}
let count = 0; // 0 is Falsy (0 زائفة)
if (count) { console.log('This will not run.'); (هذا لن يتم تشغيله.) }