# Dynamic function name in JS

> How I created a dynamic function name in JavaScript using globalThis and a random suffix, so two reCAPTCHA forms from the same Astro component don't clash.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2024-04-13 | Topics: [JavaScript](https://flaviocopes.com/tags/js/), [Astro](https://flaviocopes.com/tags/astro/) | Canonical: https://flaviocopes.com/dynamic-function-name-in-js/

I ran into a somewhat fun issue today.

On the [courses page](https://flaviocopes.com/courses/) I started listing the courses I will organize soon, each with a form.

Forms are both protected using recaptcha, and the way recaptcha works is that it needs a function name to be called upon “return” (callback) of the validation process.

I basically used this same code for years but it’s probably the first time I run 2 forms on the same page.

Having 2 [forms](https://flaviocopes.com/html-forms/) on the page means I cannot use the same function callback name.

However the form is in an [Astro reusable component](https://flaviocopes.com/astro-components/).

I thought about using a random name that’s generated any time a component is used.

To do so I had to create a random function name, using the global object.

It’s an old trick, just took me a couple minutes to figure out if this was the correct way to have a dynamic function name (this is by far the easiest I came across)

Instead of:

```javascript
function onSubmit() {
  //...
}
```

I used 

```javascript
globalThis['onSubmit' + rand] = function() {
  //...
}
```

`globalThis` pointing to the window object as I’m in the browser environment.

`rand` is the random value, I generate it server-side when the component is created (through [Astro](https://flaviocopes.com/astro-introduction/)), then pass it to the client-side script using `define-vars`:

```javascript
---
const rand = Math.random().toString(36).substr(2, 9)
---

<script is:inline define:vars={{ rand }}>
    window['onSubmit' + rand] = function() {
        document.getElementById('form-' + rand).submit()
    }
</script>
```

If I didn’t have the server-side generated part, I’d have to wrap it manually in an [IIFE](https://flaviocopes.com/javascript-iife/) to avoid name clashing any other time the component is added to the page.

And that’s exactly what happens under the hood in [Astro](https://flaviocopes.com/tags/astro/):

![Browser developer tools showing generated script tag with dynamic function name using globalThis and random suffix](https://flaviocopes.com/images/dynamic-function-name-in-js/1.webp)
