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:
<library_name>:
version: 1.x
js:
js/<your_javascript_file>.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 <module_name>_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
$form['#attached']['library'][] = '<module_name>/<library_name>';
$form['#attached']['drupalSettings']['<module_name>']['<library_name>']['variable'] = 'value';
}
To make sure, console.log your PHP variable in your_javascript_file to see it, example:
(function($){
console.log(drupalSettings.<module_name>.<library_name>.variable); // value
})(jQuery);
Hope this helps!