espresso_coffee
espresso_coffee

Reputation: 6110

How to prevent javascript if statement to evaluate 0 as an empty string?

I have js object that has data which contains numbers. Some of them can be 0. In that case if statement will evaluate those values as an empty strings. Here is example:

var dataObj = {
  "one": 13,
  "two": 0,
  "three": 3
}

$.each(dataObj, function (j, k) {
  if(k){
    console.log('Column: '+k);
  }else{
    console.log('Empty');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

I'm wondering how this can be prevented? Is there a way to check if value is empty but at the same time not consider 0 as an empty value?

Upvotes: 1

Views: 1176

Answers (2)

Mamun
Mamun

Reputation: 68933

You can add k==0 with Logical operator (||) as part of the condition which will pass through the condition when the value is 0.

Try

if(k || k == 0){

var dataObj = {
  "one": 13,
  "two": 0,
  "three": 3
}

$.each(dataObj, function (j, k) {
  if(k || k == 0){
    console.log('Column: '+k);
  }else{
    console.log('Empty');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 0

hifebriansyah
hifebriansyah

Reputation: 341

you can change the condition to k || k===0 this mean (as far as i know) it will accept not-undefined, not-null, not-empty and zero int value as a true.

please comment if there anything i can do to improve the answer..

don't forget to checkout my snippet

have a nice day..

var dataObj = {
  "one": 13,
  "two": 0,
  "three": 3,
  "four": null,
  "five": ''
}

$.each(dataObj, function (j, k) {
  // use 'or' operator
  if(k || k===0){
    console.log('Column: '+k);
  }else{
    console.log('Empty');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 2

Related Questions