Using function's return value in if statement

前端 未结 5 958
你的背包
你的背包 2021-02-09 05:54

Hopefully a quick question here.

Can you use a function\'s returned value in a if statement? I.e.

function queryThis(request) {

  return false;

}

if(q         


        
5条回答
  •  无人及你
    2021-02-09 06:21

    Not only you can use functions in if statements in JavaScript, but in almost all programming languages you can do that. This case is specially bold in JavaScript, as in it, functions are prime citizens. Functions are almost everything in JavaScript. Function is object, function is interface, function is return value of another function, function could be a parameter, function creates closures, etc. Therefore, this is 100% valid.

    You can run this example in Firebug to see that it's working.

    var validator = function (input) {
        return Boolean(input);
    }
    
    if (validator('')) {
        alert('true is returned from function'); 
    }
    if (validator('something')) {
        alert('true is returned from function'); 
    }
    

    Also as a hint, why using comparison operators in if block when we know that the expression is a Boolean expression?

提交回复
热议问题