CodeBlanks Logo Icon CodeBlanks

Module vs script

JavaScript course · Intermediate · Lesson 128/134

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

  1. 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.

  2. What is this in a module?

    console.log(____); // undefined in module
    Show answer
    console.log(this); // undefined in module
  3. Match the module behaviors

    strict mode
    automatic in modules
    defer
    runs after DOM ready
    this
    undefined in module
    top-level let
    not global

All lessons in Intermediate