Add javascript to form by module i am writing a module in drupal 8. I wish to add a javascript when loading that form. 

function ajax_example_form_alter(&amp;$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
 $form['#attached']['library'][] = array('ajax_example', 'ajax_example.sync_script');
}


and i have defined the following at the module library yml file

sync_script:
  version: 1.x
  js:
    js/test.js: {}


but seems the js is not embedded. And i have put the js in a folder called js at the root directory of the module.

What is the way for drupal 8 to embed a javascript at the form?
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!