Initialising context variables if they don't exist

JS Gurus Assemble :slight_smile:

I feel this could be done in a more JS way - can it?

if (!(context.get('blue'))) {
  context.set('blue', 'initial');

If you don't mind setting regardless:

context.set('blue', context.get('blue') || 'initial');

Will that only set it to initial if the context value doesn't exist?

The above would look for a 'true' value from context.get('blue') much like your original code and use that value if true, otherwise use 'initial'. Can run into problems if you were using numbers or something else (0 and empty strings evaluate to false for example). If you want to test for existence, I would do:

if (context.get('blue') == undefined)
  context.set('blue', 'initial');
1 Like