yunusus yunusus - 6 months ago 14
Javascript Question

How can I return boolean value from nested functions ? - Javascript

I want to learn, how can I return boolean value from nested functions at Javascript ? I want to run the next function, if previous function returns true. For example there is a main function and there is 3 sub functions.

It will be like this: run first function if it returns true, run second one and if second returns true, run third function if third function returns true mainfunction also returns true. Can someone show me a simple example for that. I wrote an example but it always returns false :) I want to learn the logical best way for that. Thanks all from now :)


My example:


var uname;

$("#username").keyup(function() {

uname = checkUsername();
console.log(checkUsername());

}); // Username keyup


function allowedChars() {

var username = document.getElementById("username").value;

var chars = /^[a-zA-Z0-9\.\_]*$/;

if(chars.test(username) == true) {

$("#notName").html("").show();

return true;

}

else {

$("#notName").html("Username can just contain A-Z, 0-9, dot and underscore!").show();

return false;

}

} // allowedChars

function unameLen() {

var username = document.getElementById("username").value;

if ((username.length > 3) && (username.length < 20)) {

$("#notName").html("").show();

return true;

}

else {

$("#notName").html("Username must be between 3 and 20 characters!").show();

return false;

}

}

function unameAvl() {

var username = document.getElementById("username").value;

$.post("check.php", { username: username },
function(result){

if (result == true) {

$("#notName").html("").show();

return true;

}

else {

$("#notName").html("Username is already exists!").show();

return false;

}

});

}

function checkUsername() {

allowedChars();

if (allowedChars()) {

unameLen();

}

if (unameLen()) {

unameAvl();

}

if (unameAvl()) {

return true

}

else {

return false;

}

}

Answer

You can use the && operator to do this for you, because it implements short-circuit boolean logic.

Change your checkUserName method to this and see how it works:

function checkUsername() {
    return allowedChars() && unameLen() && unameAvl();
}

In this case, when allowedChars returns true, it will next call unameLen. If unameLen returns true, it will call unameAvl. The checkUsername function will return false if any of the functions return false, or true if they all return true.

Comments