# Initialising context variables if they don't exist

**URL:** <https://discourse.nodered.org/t/initialising-context-variables-if-they-dont-exist/14214>\
**Category:** General\
**Created:** [11 August 2019 13:01 UTC](https://discourse.nodered.org/t/initialising-context-variables-if-they-dont-exist/14214 "2019-08-11T13:01:40Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![cymplecy](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/cymplecy/32/2773_2.png) [@cymplecy](https://discourse.nodered.org/u/cymplecy)\
**Post date:** [11 August 2019 13:01 UTC](https://discourse.nodered.org/t/initialising-context-variables-if-they-dont-exist/14214/1 "2019-08-11T13:01:40Z")

</div>

JS Gurus Assemble 🙂

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

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

```

---

<div class="post-metadata">

**Author:** ![thatcadguy](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/thatcadguy/32/5273_2.png) [@thatcadguy](https://discourse.nodered.org/u/thatcadguy)\
**Post date:** [11 August 2019 13:06 UTC](https://discourse.nodered.org/t/initialising-context-variables-if-they-dont-exist/14214/2 "2019-08-11T13:06:57Z")

</div>

If you don't mind setting regardless:

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

```

---

<div class="post-metadata">

**Author:** ![cymplecy](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/cymplecy/32/2773_2.png) [@cymplecy](https://discourse.nodered.org/u/cymplecy)\
**Post date:** [11 August 2019 13:24 UTC](https://discourse.nodered.org/t/initialising-context-variables-if-they-dont-exist/14214/3 "2019-08-11T13:24:05Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![thatcadguy](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/thatcadguy/32/5273_2.png) [@thatcadguy](https://discourse.nodered.org/u/thatcadguy)\
**Post date:** [11 August 2019 13:46 UTC](https://discourse.nodered.org/t/initialising-context-variables-if-they-dont-exist/14214/4 "2019-08-11T13:46:32Z")

</div>

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:

```auto
if (context.get('blue') == undefined)
  context.set('blue', 'initial');

```
