0

I'm trying to return 2 values from a function in javascript, to use them later. I found out this is possible using arrays.

So, I create an array with the values false(bool) and a string. When I use the console.log() command for my array inside the function right before it returns, I get exactly what I expect, an array with the two elements I put in it.

(2) [false, ''] 0: false 1: "" length: 2

[[Prototype]]: Array(0)

When I return the array, I try to put the values inside a new array (I will show code) and it throws this error:

Uncaught TypeError: validateUser is not a function or its return value is not iterable
    at HTMLFormElement.<anonymous> (login.js:8:31)
(anonymous) @ login.js:8

Here is the code: The function:

function validateUser(username, password){
    const loadRequest = new XMLHttpRequest();

    loadRequest.onload = function(){
        const info = new Array(2);
        if(this.responseText == ""){
            document.getElementById("login-error").innerHTML = "Incorrect username or password";
            info[0] = false;
            info[1] = "";
            console.log(info);
            return info;
        }
        info[0] = true;
        info[1] = this.responseText;
        return info;
    }
    loadRequest.open("GET", "validateUser.php?username="+username.value+"&password="+password.value, true);
    loadRequest.send();   
}

The data "transfer":

    const [valid, userInfo] = validateUser(username, password); 

I don't understand what the problem is. I searched for tutorials online, documentation, etc. I always see people using it like that with no problems. I searched it and all arrays are iterable so what gives. I tried changing the false into a string "false", thinking its inconsistent data types, but no. Still the same problem. I've thought of passing on a single string and using split, but that seems like such a bad solution. How would you guys solve this?

0 Answers0