Add javascript to form by module
I don't know what you're aiming to build.

Because I think it's not good to use your javascript in hook_form_alter() , that way, any form you try to see will invoke that javascript code.

However... Back to your issue,

I think the hook_form_alter() function should be used in the module_name.module file under the root of your module folder: modules/custom/module_name/module_name.module along side the routing, info, etc.

After building the .module file, you need to build the module_name.libraries.yml file (if it's not already built), and there, you write your routing requirements, example:

&lt;route_name&gt;:
  version: 1.x
  js:
    js/&lt;your_javascript_file&gt;.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings


Backto the .module file, you implement the hook_form_alter, so your code goes like this:

/**
 * Implements hook_form_alter().
 */

function &lt;module_name&gt;_form_alter(&amp;$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){

    $form['#attached']['library'][] = '&lt;module_name&gt;/&lt;route_name&gt;';
    $form['#attached']['drupalSettings']['&lt;module_name&gt;']['&lt;route_name&gt;'] ['variable'] = 'value';

    return $form;

}


To make sure, console.log your PHP variable in your_javascript_file to see it, example:

(function($){
    console.log(drupalSettings.&lt;module_name&gt;.&lt;route_name&gt;.variable); // value
})(jQuery);


Hope this help!