Search the Drupal 8 HowTo.

How to create a library dynamically in Drupal 8.

In Drupal 8, javascript can not be attached to forms and render objects inline. JS can only be attached as library. However, what if you need to add a dynamic js, that changes based on conditions? This is where dynamic libraries step in with hook_library_info_build().