How do I send a variable from PHP to JavaScript from a function that returns a render array? I'm trying to send a variable to my JavaScript. I would like to send a class name to my twig template and the same class-name to my javascript from a function that returns a render array. The function is called from a routing yml to display a page from a link in a page (which is beside the point).
The returned render array is similar to the following one.
return [
  '#theme' =&gt; 'theme_name',
  '#form' =&gt; $form,
  '#data' =&gt; [
    'customer' =&gt; $obj_customer,
    'customer_subscription' =&gt; $obj_customer-&gt;getSubscription(),
    'subscriptions_explanation' =&gt; $arr_subscription_text,
  ]
];

Passing data from PHP to javascript variable available to all pages in Drupal 8 says you can do something with '#attached' =&gt; ['drupalSettings' =&gt; ['do' =&gt; $something]] in hook_page_attachments(), but that doesn't seem to apply to the method I am using.
How can I do in my case? Adding stylesheets (CSS) and JavaScript (JS) to a Drupal theme doesn't seem to cover this use case.
In my JavaScript I define my JS functions inside:
(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.portalCore = {
    someFunction() {
      ...
    }
  };
});

Is there perhaps a way to attach a variable to the portalCore from my example code?
EDIT (edited):
After applying kiamlaluno's answer: So If I call the drupalSettings in the console I see my assigned variable in there. But if I try to reach that variable from within (function ($, Drupal, drupalSettings) {} I get a cannot read property of undefined, obviously as logging drupalSettings logs undefined. When I remove the drupalSettings from (function ($, Drupal, drupalSettings) {}, I can reach my variable through drupalSettigs.myVar.
I, obvjously, should have included the drupalSettings in the final parentheses of the closure, like so (thank you @kiamlaluno):
(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.portalCore = {
    attach(context, settings) {
      ...
    },
    functionName() {
      // Do stuff
    },
  };
})(jQuery, Drupal, drupalSettings);
It does apply to the method you are using. You can add metadata like #cache or #attached to any render element (#theme, #type, #markup, #plain_text):
return [
  '#theme' =&gt; 'theme_name',
  '#form' =&gt; $form,
  '#data' =&gt; [
    'customer' =&gt; $obj_customer,
    'customer_subscription' =&gt; $obj_customer-&gt;getSubscription(),
    'subscriptions_explanation' =&gt; $arr_subscription_text,
  ],
  '#attached' =&gt; ['drupalSettings' =&gt; ['do' =&gt; $something]],
];