Conditional Operators in JavaScript

JS - Conditional Operators
इस operator को Ternary भी कहते है, और यह if-else statement की तरह ही work करता है, इसे हम एक लाइन में if-else statement भी कह सकते है इसमें तीन condition होती है, यदि पहला condition अर्थात् Question mark से पहले एक condition होती है| यदि ये condition true होती है तो दूसरा Condition अर्थात् colon के पहले वाला statement result के रूप में return करता है और यदि false होती है तो तीसरा Condition अर्थात् colon के बाद वाला statement result के रूप में return करती है|

Syntax :- condition1 ? condition2 : condition3


Exp:-
a= (5>3)?5:3;
print :- 5

a=(5<3)?5:3
print :- 3

Q :- Write a JavaScript Program to print the maximum number by inputting two numbers with the help of Conditional Operator.


Source Code :

<!DOCTYPE html>
<html>
<head>
<title>Maximum Number</title>
</head>
<body>
<script type="text/javascript">
	
var a=0,b=0,max=0;

a=window.prompt("Enter a Value",10);
b=window.prompt("Enter b Value",15);

a=parseInt(a);
b=parseInt(b);

max=(a>b)? a:b;

document.write("a : "+a+"<br>");
document.write("b : "+b+"<br>");

document.write("Maximum Number : "+max+"<br>");

</script>
</body>
</html>

Output :-

a : 10
b : 15
Maximum Number : 15

Q :- Write a JavaScript Program to print the minimum number by inputting two numbers with the help of Conditional Operator.


Source Code :

<!DOCTYPE html>
<html>
<head>
<title>minimum Number</title>
</head>
<body>
<script type="text/javascript">
	
var a=0,b=0,mini=0;

a=window.prompt("Enter a Value",10);
b=window.prompt("Enter b Value",15);

a=parseInt(a);
b=parseInt(b);

mini=(a<b)? a:b;

document.write("a : "+a+"<br>");
document.write("b : "+b+"<br>");

document.write("Minimum Number : "+mini+"<br>");

</script>
</body>
</html>
		

Output :-

a : 10
b : 15
Minimum Number : 10

Q :- Write a JavaScript program to check leap year with the help of conditional operator.


Source Code :

<!DOCTYPE html>
<html>
<head>
<title>Leep Year</title>
</head>
<body>
<script type="text/javascript">
	
var y=0,result=0;

y=window.prompt("Enter Any Year",2020);

y=parseInt(y);

result=(y%4==0)? ('Leep Year') : ('Not Leep Year');

document.write("Year = "+y+" "+result);

</script>
</body>
</html>

Output :-

Year = 2020 Leep Year

Q :- Write a JavaScript program to check odd and Even Number with the help of conditional operator.


Source Code :

<!DOCTYPE html>
<html>
<head>
<title>Leep Year</title>
</head>
<body>
<script type="text/javascript">
	
var n=0,result=0;

n=window.prompt("Enter Any Number",10);

n=parseInt(n);

result=(n%2==0)? ('Even Number') : ('Odd Number');

document.write("N = "+n+" "+result);

</script>
</body>
</html>

Output :-

N = 10 Even Number

Post a Comment

If you have any doubts,Please let me know

close