[SalesForce] Failing to catch empty string with if statement

Having some trouble with Javascript values in a Lightning Component Controller/Helper.

This function is part of a form. Before submission, it goes over required fields and checks if they're empty so it can decide whether or not to submit. Here's the code in question:

outer:
        for(var i = 0; i < list.length; i++){
            inner:
            for(var j = 0; j < list[i].length; j++){
                var req = list[i][j]['required'];
                if (req) {
                    var val = list[i][j]['val'];
                    // This 'if' is the offender:
                    if ((val==''||val==' '||val.length==0||val==undefined||val==null) && val!=0) {
                        valid = false;
                        console.log('VALUE \''+val+'\' INVALID @ '+i+':'+j);
                        break outer;
                    } else {
                        console.log('TEMP1: '+i+':'+j+':'+val);
                        console.log('TEMP2: '+(typeof val));
                    }
                }
            }
        }

What this if statement is supposed to do is check for empty fields, while allowing zero values (because zeroes are valid answers). Val may be a string or a number when it comes through.

Here's the output during runtime:

TEMP1: 3:2:10000
TEMP2: number
TEMP1: 3:3:10000
TEMP2: number
TEMP1: 3:6:
TEMP2: string
TEMP1: 3:7:
TEMP2: string
TEMP1: 3:10:
TEMP2: string
TEMP1: 3:11:1
TEMP2: number
TEMP1: 3:12:Yes
TEMP2: string
TEMP1: 3:13:1000
TEMP2: number
TEMP1: 3:14:50
TEMP2: number
TEMP1: 3:15:55
TEMP2: number

As you can see, the output for indeces 6, 7, and 10 output empty strings in console, but that is somehow not caught by the if statement above? What value could val have that allows it to skip that if statement but still print out that empty string?

Best Answer

Issue is that in JavaScript following statement is true:

 (0 == '')

In your scenario, if val is empty string, then in condition

((val == ''|| val == ' ' || val.length == 0 || val == undefined || val == null ) && val != 0) 

last operand will be evaluated as false, since 0, '', null are equal using '==' operator.

To make it working, it will be better to use '===' (strict comparison). For example:

if ((val==='' || val===' '|| val.length===0 || val == null ) && val !== 0 ) 

Nice links to read: