Hi there!
Tim here from the Zapier Support Team with a way to improve your Code by Zapier Steps.
A common question that I see relating to Code Steps is how to prevent them from erroring when a value mapped into the Input Data fields sometimes comes through as empty.
Let’s consider this Python Code Step:
![](https://uploads-us-west-2.insided.com/zapier-ca/attachment/8447a49e-2d9b-42c9-9a6a-94f957cad540.png)
If we try to test it, we get KeyError: 'value3'
This is because when the contents of an Input Data field are empty, the key for that particular field isn’t created in the input_data
object, so we’re trying to access something that isn’t there. The Input Data fields from the example above would create an object in the Code environment that looks like this: input_data = {"value1”: "hello", "value2": "world}
We can see that because value3
was empty, it wasn’t added to the input_data
object.
Knowing this, we can catch the error and assign a default value instead. In Python, this could look like a try: except:
Block. For example:
![](https://uploads-us-west-2.insided.com/zapier-ca/attachment/9646caa3-2fd7-4dfa-bd75-c96ad24436c2.png)
This gives us the following result:
![](https://uploads-us-west-2.insided.com/zapier-ca/attachment/88ee9710-e190-4002-a2fa-5f9d0bb8bad1.png)
As you can see, value3
came through with a default value that we set instead of causing the Step to error.
With Javascript, we can use a similar solution where we can check if the value exists (evaluates to true in an If
statement) and assign a default value if it doesn’t:
![](https://uploads-us-west-2.insided.com/zapier-ca/attachment/8e49914d-0a26-4fbb-9804-4a3f8335bfed.png)
Here’s an alternate, more condensed way that you could write this in Javascript:
![](https://uploads-us-west-2.insided.com/zapier-ca/attachment/1104eb18-c54f-45df-9eab-41ae4471573a.png)
In this example, I created an array of the my Input Data value names so that I can use a loop to check if each one exists and set the same default value for each one that’s missing. This could be useful if you wanted the default for all missing values to be something like `0` or an empty String `""`. Both version of the Javascript give us a similar output to the Python example:
![](https://uploads-us-west-2.insided.com/zapier-ca/attachment/4bdd5bac-c4df-4fa1-ba31-5afbbcf0cd63.png)
I hope you find this useful in getting your Zaps with Code to run more smoothly. Let me know what questions you have about this in the comments!
Please note
We aren't always able to help with Code questions via Zapier Support because not everyone on the Support Team is familiar with Javascript and Python, and supporting custom code is technically outside of our scope of support. A great place to ask if we can't support you directly is here in our community or on Stack Overflow by tagging your question "Zapier": https://stackoverflow.com/questions/tagged/zapier