Module vs script
Learn the differences between module and script (strict mode etc.) with type='module'.
Module vs script
Modules run in strict mode automatically. This turns on safer rules without you writing "use strict".
For example, assigning to an undeclared variable (x = 5; without let) throws an error. This prevents silent bugs.
In old-style script files strict mode is not the default; in modules it is mandatory.
Deferred loading
Modules are deferred by default. This means the browser runs the module only after it has fully parsed the HTML.
So calls like document.querySelector work because the elements are ready. Old scripts needed a defer attribute; modules have it built in.
Modules also always load with CORS requests.
Exercise Module top level
In a module, declare const VERSION = "1.0", then log the value of this at the top level with console.log.
Show example solution
Declare a const and log this with console.log.
Example solution:
const VERSION = "1.0";
console.log(this);
Test yourself
-
In which mode do modules run automatically?
- Strict mode
- Sloppy mode
- Half mode
- Random mode
Show answer
Strict mode — Correct! Modules run in strict mode by default.
-
What is this in a module?
console.log(____); // undefined in moduleShow answer
console.log(this); // undefined in module -
Match the module behaviors
- strict mode
- automatic in modules
- defer
- runs after DOM ready
- this
- undefined in module
- top-level let
- not global