Is there a way to make the following JavaScript if..else condition short, instead of writing if() else()
function two times is there any way to write if(x,y = ""){} else{}
or something similar to make it shorter ?
$(document).ready(function(){
$("#third").click(function(){
var xxx = $("#first").val();
var xxy = $("#second").val();
if (xxx == "") {
alert("good");
}
else {
alert("bad");
}
if (xxy == "") {
alert("good");
}
else {
alert("bad");
}
});
});
Is there a way to make the following JavaScript if..else condition short, instead of writing if() else()
function two times is there any way to write if(x,y = ""){} else{}
or something similar to make it shorter ?
$(document).ready(function(){
$("#third").click(function(){
var xxx = $("#first").val();
var xxy = $("#second").val();
if (xxx == "") {
alert("good");
}
else {
alert("bad");
}
if (xxy == "") {
alert("good");
}
else {
alert("bad");
}
});
});
Share
Improve this question
edited Aug 1, 2013 at 13:05
Deepak Kamat
1,9805 gold badges24 silver badges41 bronze badges
asked Aug 1, 2013 at 9:58
Aumkar ThakurAumkar Thakur
1882 gold badges2 silver badges13 bronze badges
4
|
5 Answers
Reset to default 7Use the "or" syntax (||
)
if(xxx == '' || yyy == '')
{
alert("good");
}
else
{
alert("bad");
}
This way, if xxx
is an empty string OR yyy
is an empty string, it will alert "good". If neither of them are empty, it will alert "bad"
No, you cannot write a condition like that, instead you can write it as
if(xxx == '' || yyy == '') {}
Or
if(xxx == '' && yyy == '') {}
Here, ||
is an OR operator and &&
is AND operator, the difference is 1st will return true if 1 condition satisfies, 2nd one will return true if both condition satisfies.
If you are looking for a short hand syntax, you can use ternary operator
What about this?
$(document).ready(function() {
var showResult = function(val) {
alert(val ? "good" : "bad");
};
$("#third").click(function(){
var xxx = $("#first").val();
var xxy = $("#second").val();
showResult(xxx);
showResult(xxy);
});
});
If you want just to combine, you can write even less:
$(document).ready(function() {
$("#third").click(function(){
var xxx = $("#first").val();
var xxy = $("#second").val();
alert((xxx || xxy) ? "good" : "bad");
});
});
and if you want the shortes code, i think it could be like this:
$(document).ready(function() {
$("#third").click(function(){
var elems = $("#first, #second").val();
alert((elems[0] || elems[1]) ? "good" : "bad");
});
});
Demo
if(xxx=="" && xxy == ""){
alert('good');
}else if(xxx!="" || xxy != ""){
alert('bad');}
You can write it like this
xxx=="" && xxy =="" ? alert("good") : alert("bad")
if (!xxx || !xxy) //...
? (empty strings evaluate to false). – James Allardice Commented Aug 1, 2013 at 9:59if(x == '' && y == '')
? – putvande Commented Aug 1, 2013 at 10:00