'undefined' value on an empty array element

ubido
Mega Expert

Dear folks,

I’m working on a workflow in which I’m collecting a list of user selected options in an array of a predetermined size. So if the Array_A holds a maximum of five elements, but the user only selects three options I’m using a branch to pass the five elements of the array to five “if” conditions.


In each of the if conditions I have the following script:


answer = ifScript();
function ifScript() {
if (Array_A[0] != '') {
return 'yes';
}
return 'no';
}

And in each if condition I change the reference to the array element (Array_A[1], Array_A[2] and so on). For those array entries that are storing a value ‘yes’ is being selected in the if and the workflow proceed as expected; but for those that nothing was selected instead of an empty element (‘ ‘) I get ‘undefined’ and the if return ‘yes’ as well instead of ‘no’.

How do I define the array so that each element have the ' ' until a user selected value is added to it?  I can share more of the code I'm working on if necessary.

Regards,

ubido

1 ACCEPTED SOLUTION

That is my bad. Yes, use '||' instead of '&&'. So basically if the value is empty string OR undefined. 

View solution in original post

4 REPLIES 4

Konstantin7
Mega Guru

So basically, the Array_A could have a length of 1 through 5. If the user only selected 3, the length of the array is 3. Therefore, when the IF condition is checking Array_A[3], it will be undefined. Have your IF condition checking for undefined. If you want to be sure, have it check against undefined AND empty string.

if(Array_A[0] != '' && Array_A[0] != undefined) {}

Thanks for your reply Konstantin,

I that the proper way to test for an undefined value?  Because I tried that and it's not working.  Also, why do you suggest an '&&' instead of an '|'? Can the value of Array_A[N] be empty and undefined at the same time?

Regards!

That is my bad. Yes, use '||' instead of '&&'. So basically if the value is empty string OR undefined. 

Thanks Konstantin!  I got it working now, but I had to change the test for 'undefined' to get it to work but I really appreciate you sending me in the right direction:

answer = ifScript();
function ifScript() {

if (Array_A[0] == '' || typeof Array_A[0] === 'undefined') {
    return 'no';
}
return 'yes';

}

Best regards,

ubido