जावास्क्रिप्ट में तीन प्रकार के कंडीशनल स्टेटमेंट होते हैं -
- यदि कथन - if स्टेटमेंट का उपयोग if ब्लॉक के अंदर कोड को निष्पादित करने के लिए तभी किया जाता है जब विशिष्ट शर्त पूरी होती है।
- यदि अन्य कथन - द इफ….एल्स स्टेटमेंट का उपयोग केवल दो स्थितियों की जांच करने और उनमें से प्रत्येक के लिए अलग-अलग कोड निष्पादित करने के लिए किया जाता है।
- यदि कोई और कथन हो तो − अगर…else if…else स्टेटमेंट का इस्तेमाल दो से ज्यादा कंडीशन चेक करने के लिए किया जाता है।
जावास्क्रिप्ट में सशर्त बयानों को लागू करने के लिए कोड निम्नलिखित है -
उदाहरण
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 20px;
font-weight: 500;
color: blueviolet;
}
</style>
</head>
<body>
<h1>Conditional statements in JavaScript</h1>
<input type="text" class="numInput" />
<button class="Btn">CHECK</button><br />
<div class="result"></div>
<h3>Click on the above button to see if the above number is divisible by 2,3 or both</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelector(".Btn");
let numInputEle = document.querySelector(".numInput");
BtnEle.addEventListener("click", () => {
if (numInputEle.value % 2 === 0 && numInputEle.value % 3 === 0) {
resEle.innerHTML = "The numbers is divisible by 2 and 3 both";
} else if (numInputEle.value % 3 === 0) {
resEle.innerHTML = "The number is divisbly by 3";
} else if (numInputEle.value % 2 === 0) {
resEle.innerHTML = "The numbers is divisible by 2";
} else {
resEle.innerHTML = "The numbers isn't divisible by 2 or 3";
}
});
</script>
</body>
</html> आउटपुट

एक नंबर दर्ज करने और 'चेक' बटन पर क्लिक करने पर -
