इस उदाहरण में, आप एक जावास्क्रिप्ट प्रोग्राम लिखना सीखेंगे जो यह जाँच करेगा कि एक चर अपरिभाषित या अशक्त है या नहीं।
इस उदाहरण को समझने के लिए, आपको निम्नलिखित जावास्क्रिप्ट प्रोग्रामिंग विषयों का ज्ञान होना चाहिए:
- जावास्क्रिप्ट शून्य और अपरिभाषित
- जावास्क्रिप्ट टाइपो ऑपरेटर
- जावास्क्रिप्ट फंक्शन और फंक्शन एक्सप्रेशन
उदाहरण 1: अपरिभाषित या अशक्त की जाँच करें
// program to check if a variable is undefined or null function checkVariable(variable) ( if(variable == null) ( console.log('The variable is undefined or null'); ) else ( console.log('The variable is neither undefined nor null'); ) ) let newVariable; checkVariable(5); checkVariable('hello'); checkVariable(null); checkVariable(newVariable);
आउटपुट
चर न तो अपरिभाषित है और न ही अशक्त है, न ही चर अपरिभाषित है और न ही अशक्त है, अपरिभाषित या अशक्त है चर अपरिभाषित या अशक्त है
उपरोक्त कार्यक्रम में, एक चर की जाँच की जाती है यदि यह इसके बराबर है null
। null
साथ ==
दोनों के लिए चेक null
और undefined
मूल्यों। ऐसा इसलिए है क्योंकि null == undefined
सच का मूल्यांकन करता है।
निम्नलिखित कोड:
if(variable == null) (… )
के बराबर है
if (variable === undefined || variable === null) (… )
उदाहरण 2: टाइपोफ़ का उपयोग करना
// program to check if a variable is undefined or null function checkVariable(variable) ( if( typeof variable === 'undefined' || variable === null ) ( console.log('The variable is undefined or null'); ) else ( console.log('The variable is neither undefined nor null'); ) ) let newVariable; checkVariable(5); checkVariable('hello'); checkVariable(null); checkVariable(newVariable);
आउटपुट
चर न तो अपरिभाषित है और न ही अशक्त है, न ही चर अपरिभाषित है और न ही अशक्त है, अपरिभाषित या अशक्त है चर अपरिभाषित या अशक्त है
typeof
के लिए ऑपरेटर undefined
मूल्य रिटर्न अपरिभाषित। इसलिए, आप ऑपरेटर undefined
का उपयोग करके मूल्य की जांच कर सकते हैं typeof
। साथ ही, ऑपरेटर null
का उपयोग करके मूल्यों की जांच की जाती है ===
।
नोट : हम typeof
ऑपरेटर का उपयोग नहीं कर सकते null
क्योंकि यह ऑब्जेक्ट लौटाता है।