How do I pass variables to JavaScript?
Instead of drupal_add_js(array('MODULENAME' =&gt; array('testvar' =&gt; $testVariable)), array('type' =&gt; 'setting')); you use $build['#attached']['drupalSettings']['testvar'] = $testVariable;. Replace $build with the variable containing the form or the render array to which the settings are attached; in a form builder or hook_form_alter(), that would be $form.

The JavaScript code to attach to the page should then be defined as library, which is the only way to attach JavaScript and CSS to a page or a form.
It is explained in Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module, so I will not repeat it here. I will just make notice that the library needs to declare at least two dependencies:


core/jquery, if the JavaScript code uses jQuery
core/drupalSettings, since the JavaScript code uses Drupal settings