Is it possible to check if a variable exists

I want to return an object which would have dynamic fields. Sometimes I get Var(‘rewards’) is undefined because it is called at a point which is before the Var(‘rewards’) is defined.

Is it possible to do something like this?

function returnData(code) {
    return {
        code,
        additional
        pools: If(Not(IsNull(Var('pools'))), Do(Var('pools')), null),
        poolRand: If(Not(IsNull(Var('poolRand'))), Do(Var('poolRand')), null),
        poolWeight: If(Not(IsNull(Var('poolWeight'))), Do(Var('poolWeight')), null),
        rewards: If(Not(IsNull((Var('rewards')))), Do(Var('rewards')), null),
        rewardRand: If(Not(IsNull(Var('rewardRand'))), Do(Var('rewardRand')), null),
        rewardWeight: If(Not(IsNull(Var('rewardWeight'))), Do(Var('rewardWeight')), null),
    }
}

Hi @Vinn_Silva,

I’m not really sure what you’re trying to do here. Do() is used to run a sequential list of tasks, but it looks like you’re using it here to set values on elements in a document. If you’re just setting the individual elements to those values then you don’t need Do(), or Get() for that matter. Just referencing the Var() will be enough.

Keep in mind that null values are not stored in Fauna. Setting rewards: null is the same as not setting rewards at all in the first place. So if your Var('rewards') is equal to null, that attribute simply won’t be set in the document, so there’s no need to test for its existence prior to setting it.

So really all you need is:

function returnData(code) {
    return {
        code,
        additional
        pools: Var('pools'),
        poolRand: (Var('poolRand'),
        poolWeight: Var('poolWeight')
        rewards: Var('rewards'),
        rewardRand: Var('rewardRand'),
        rewardWeight: Var('rewardWeight')
    }
}

Cory

Yeap the Do was pointless. Thanks for pointing that out. I solved it by initializing the variable at the beginning to null. Thank you.