Help with reading any context value and the "check not null" option

I just wasted about 45 minutes on a stupid mistake - again.

So, I am reading a context value, and need it to be something rather than undefined.

If it is a number, the option is something like:

let x = context.get("blah") || 0;

Which means if blah isn't set (for what ever reason) x is given the value of 0.

I'm not exactly sure about text, but for now, I will let that go (though I know it will bite me soon).

Say I am doing something and it has a valid range of 0 - 255.
So 0 is as valid as 1, or 255.

But I want the value returned if the context isn't set to be .... say 123. (Half 255)

How do I do that?

I can't set it to 0 then say if == 0 make it 123 because if it is 0 it will be changed to 123.

I am missing something it would seem.

Did you try
let x = context.get("blah") || 123;

Yes, and it drove me around the twist for 45 minutes because when blah was equal to 0 it got changed to 123. Or something like that.

Then I realised what was going on and make the last part || 0 and the problem went away.

That’s right, the retrieved value is evaluated. Zero (0) evaluates to false so it would then use the 123. It’s JavaScript coercion:

  • A || B returns the value A if A can be coerced into true ; otherwise, it returns B .

Ok, thanks.

It would seem I didn't understand the problem and so asked the wrong question - way back then.

The solution I was given worked for that case and as a result I (wrongly) used it for other cases.

Without wanting to start a new thread, can someone help me with this new question:

I want a line (or so) of code (I hope one) that can be used when testing the existence of context variables. (context, flow or global)

I want to test for the existence and if the variable doesn't exist returns something.
This could be text, number or logic (true/false)

Then I could maybe use it in future in stead of that which I am using and avoiding the mistake/s I made today from happening again.

The || value technique only works if value is zero or if zero is not a valid value for your system. If you need to initialise it to 123 and 0 is a valid value then you need to get it and then test for undefined using an explicit if test such as if (x == undefined) {

1 Like

Hi @Trying_to_learn

If a value doesn't exist, then the call to context.get("blah") will return undefined.

You will need to explicitly test for that:

let x = context.get("blah");
if (x === undefined) { x = 123; }
2 Likes

Thanks @knolleary and @Colin.

I shall roll that out as my way of testing from now on.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.