Reputation: 77
I'm trying to return variables as true or false via a function. I want to do it this way so I can call ajax only once, and receive both variables back in one function. However, I'm having trouble returning the variable. Here is my code:
var emailExists = false;
var userExists = false;
function checkExisting(emailExists,userExists) {
var emailExists = true;
return emailExists;
}
alert(emailExists);
What I can't figure out is why the alert gives me false, when I thought it'd be giving me true. What's wrong with this setup?
Upvotes: 0
Views: 118
Reputation: 13533
You have 3 versions of the "emailExists" variable: the global one, the parameter to checkExisting(), and the local one in checkExisting()! Get rid of all but the first one. Also, you never call checkExisting().
var emailExists = false;
function checkExisting() {
emailExists = true;
}
checkExisting();
alert(emailExists);
or
var emailExists = false;
function checkExisting() {
return true;
}
emailExists = checkExisting();
alert(emailExists);
Upvotes: 1
Reputation: 10645
In short... everything.
I take it you are new to javascript and programming? You need to do a lot of reading so that you understand object scope and how javascript works. I'll give you a quick run-through of what you have written so you can hopefully learn something.
// Here you're declared two objects. 'emailExists' and 'userExists'.
// These Boolean objects, since they are not wrapped in a closure are now global
// (you can reference them anywhere) in your script.
var emailExists = false;
var userExists = false;
// This function never gets called. If it did, it would always return true
// since you have created a new 'emailExists' Boolean object in your function
// and would return that each time.
function checkExisting(emailExists,userExists) {
// This whilst only available within the function closure, is a no, no.
// You're just confusing things by creating objects with the same name
// as global ones.
var emailExists = true;
// I'm returning true.
return emailExists;
}
// Here you are returning your first declared Boolean (the one at the top)
// this will always return false.
alert(emailExists);
Upvotes: 0
Reputation: 13545
var emailExists = false;
var userExists = false;
function checkExisting(emailExists,userExists) {
emailExists = true;
return emailExists;
}
checkExisting(false,true); //FOR EXAMPLE !
alert(emailExists);
You should call checkExisting function, and not needed use from var
into body of function, because it's defined on page .
Upvotes: 0