شبكة تعلم مع ناو

كيف أقرأ خاصية من كائن قد يكون null في JavaScript؟ (?.)

استخدم الربط الاختياري (Optional Chaining) ?.:

let personObject;

const name = personObject?.name;  // undefined, no error

من دونه، الكود التالي يوقف البرنامج بخطأ:

personObject.name;
// TypeError: Cannot read properties of undefined

كيف يعمل؟

إذا كان ما قبل ?. هو null أو undefined، يتوقف التعبير ويعيد undefined بدل أن يحاول القراءة.

استخدامات مفيدة

user?.address?.city          // nested
user?.getName?.()            // call only if it exists
const city = user?.address?.city ?? 'Unknown';  // with a default

اختبر نفسك

خمسة أسئلة سريعة، مع الإجابة والشرح بعد كل سؤال.