Declaring Variable in For Loop


#1

I’ve been working on a script to allow me to add a contact to a contacts group based on the content of that contact’s note field. I put it up on GitHub here I’m running into an issue with line 68 of the script where Scriptable can’t find the variable group though I declared it in an earlier For loop. In Javascript, do variables in loops not persist? And if not, does anyone have a suggestion for a better way to do this?


#2

I believe let has a more limited scope than var, but you are not using let… so could it be that your if condition is not being met to create the variable?

Maybe try console logging something when the condition is met to ensure your variable should be created. But also consider your logic for what you have. If there is any chance you are not creating a variable, you should never try to reference it.


#3

Somehow in the version on github, I had var, but in Scriptable I had let. It works now. :man_shrugging:t2:

Now, next question:

Is there a function in Scriptable to end the script. So if a user selects Cancel in my script, the script ends? Or is that going to require reworking my whole script into an if statement?


#4

See Script.complete().

https://docs.scriptable.app/script/

But also consider restructuring too.


#5

Also, github has been updated if anyone else wants to use this script. I just don’t have a contingency in place for if the user cancels the action. Currently, the script creates a group with a blank title and no contacts if the user cancels.


#6

I just noticed an answer to my question in this thread right next to mine. :man_facepalming:t2:

This place is the best. Script update coming soon.


#7

If you want, you could do const group = allGroups.find(group => group.name === userGroup). That will return the group if it finds a match, or it will return null if no match is found. It simplifies the code to a single line too