The JavaScript

The first thing we need to do inside the JavaScript file is to wrap the entire code we write in the file into an immediately invoked function expression (IIFE). In doing this, we protect the scope of what we write from the global one and even use global variables with more commonly associated variable names inside our own scope. This is how this looks:

(function (Drupal, $) {

 "use strict";

 // Our code here.

}) (Drupal, jQuery);

The most important thing here is that inside this function we can now use the dollar sign ($) as a reference to the global jQuery object without interfering with other libraries that might use the same variable name. Also, we added the use strict declaration to ensure we write semantically correct code ...

Get Drupal 8 Module Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.