Search code examples
marklogicserverside-javascript

if() handles booleans in a strange way


We are talking server side java script here on the MarkLogic platform. Now I am confused:

// query

function testBoolean(){
 return false
}

if(testBoolean()){'true'} else {'false'}

gives the string "false" as testBoolean() is of type Boolean.

Now my own function returns also a boolean but I need an explicit comparison before if() figures it out...

function userExists(userName) {
    // check if user exists in security database
    var data = {userName : userName}
    var options = {
               "database" : xdmp.securityDatabase()
                };
    var res = xdmp.eval("declareUpdate(); var sec = require('/MarkLogic/security.xqy'); sec.userExists(userName)",
                                data,options);
    return res
};

// make sure result is actually aboolean
// xdmp.type(userExists('scc-user-1'))

if(userExists('notextistinguser')){ 'true' } else {'false'}

gives the string "true" ???

The user 'notextistinguser' does not exist(duhhh), the function returns a type boolean of value 'false' and still this passes as true. I tried looking at the 'different-transaction' option.

When I compare explicitly in need to cast the false to a string?

userExists('notextistinguser')=='false' 

So what type is my custom function now? It reports boolean but acts as a string?


Solution

  • Change your last line to be:

    if(fn.boolean(userExists('notextistinguser'))){ 'true' } else {'false'}
    

    or change the return on your function to be :

    return fn.boolean(res)
    

    That returns the correct result now.


    fn.boolean() will convert that into an actual JavaScript boolean for you.

    Here are some results from testing:

    typeof(userExists('notextistinguser')) //Returns Object
    
    typeof(fn.boolean(userExists('notextistinguser'))) //Returns Boolean
    

    https://docs.marklogic.com/fn.boolean