Declaring Variable in For Loop

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?

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.

1 Like

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?

1 Like

See Script.complete().

But also consider restructuring too.

1 Like

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.

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.

1 Like

If you want, you could do const group = allGroups.find(group => === 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