Add JavaScript file/library and JavaScript setting in a renderable array by using #attached property

Last updated on 19/04/2018

Here is an example which is self explanatory:

Drupal 8

$form['#attached'] = [
    // Add the library(usually defined in your *.libraries.yml).
    'library' => [
      'car/visibility'
    ],
    // Add the JS configurations accessible via drupalSettings.car.
    'drupalSettings' => [
      'car' => $has_data
    ]
];

Drupal 7

$form['#attached']['js'] = [
  // Add a JS file.
  'car_visibility' => drupal_get_path('module', 'car') . '/car.admin.js',
  // Add the JS configurations accessible as Drupal.settings.car
  [
    'data' => [
      'car' => ['hasData' => $has_data],
    ],
    'type' => 'setting',
  ],
];