1

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?

6
  • 1
    How about if (k || k === 0)? Commented Dec 12, 2018 at 14:57
  • That works but is that a good practice? Commented Dec 12, 2018 at 14:58
  • 3
    Why wouldn't it be? It's guaranteed to behave in a specific way by the language spec. Commented Dec 12, 2018 at 14:59
  • 1
    So do not do a truthy check? Check for an empty string? if (k != '') Commented Dec 12, 2018 at 15:03
  • 1
    Is not evaluating as empty string. There are numerous falsy values beyond empty string and 0 is one of them Commented Dec 12, 2018 at 15:05

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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>

2 Comments

Sorry, but this a duplicate of a previous answer (and should be a comment anyway, given that this is a question about good practice, not really about solving a problem)
@ChrisG, why the comment is only under one answer not under another.....voting to close would be more meaningful than commenting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.