Reputation: 11
In the below program i am using 3 if conditions, but the if statement in the middle doesn't works and last if statement works fine,when I change third if statement to second statement again second statement is not working properly. Third if statement works fine
function calculate() {
var quantity = document.getElementById("quantity").value;
var price = document.getElementById("price").value;
var discount = document.getElementById("discount").value;
var tax = document.getElementById("tax").value;
if((quantity && price ) != null) {
amount = quantity * price;
document.getElementById("amount").value = amount;
} else {
alert("price & tax required");
}
if(discount != null) {
var discount_amount = (quantity*price*discount)/100;
amount = (quantity*price) - discount_amount;
document.getElementById("amount").value = amount;
} else {
document.getElementById("amount").value = quantity * price;
}
if(tax != null) {
var tax_amount = (quantity*price*tax)/100;
amount = (quantity*price) + tax_amount;
document.getElementById("amount").value = amount;
} else {
document.getElementById("amount").value = quantity * price;
}
}
Upvotes: 0
Views: 250
Reputation: 485
if(discount != null)
lets assume discount variable is empty string. What do you thnik about result ?
if(""!=null)
It will be true
What if your string comes fullfiled with some data
if("someData"!=null)
It will be true
again.
I do not blame you. Javascript has some magical act in these kinds of situation.
In javascript, there is a lot of logic operation that can represent as false
for if condition. Below code, all if
statements return false
if(""){//code here}
if(null){//code here}
if(0){//code here}
A developer should not compare two different types like null
and string
.
Just in case, I advise you to avoid double equal sign ==
. Use triple ===
it is type-sensitive .
see here
Upvotes: 0
Reputation: 5041
You don't need to explicitly check for null in any of your if
tests, as zero values as well as undefioned
if (quantity && price) {
// only want to come in here for non-zero values of both
}
if (discount) {
// only interested in the discount for non-zero values
}
if (tax) {
// only interested in non-zero values of tax
}
Upvotes: 0
Reputation: 106
if(discount != null)
discount will be empty string and not null check for:
if(discount !== "")
Upvotes: 0
Reputation: 386624
input.value
returns a string, which is never null
, but it can be an empty string, like ''
.
Empty strings a converted to zero in numerical context. If that is not wanted, you need an explicit check, like
if (input.value === '') {
return;
}
Upvotes: 2