Modules (import/export, concept)

Computer Science · JavaScript

Question 1 of 10

0

    A dynamic import(“./chart.js”) call returns:

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Modules (import/export, concept) explained

    Modules split a program into files that each have their own scope. A module shares only the values it exports, and other files bring them in with import, so code can be reused without placing every variable in the global scope.

    A module marks values with export, for example export const rate = 0.2 or export function withTax. Another module imports them by name in braces, such as import { withTax } from "./math.js". A default export is imported without braces.

    // math.js
    export const TAX = 0.2;
    export function withTax(price) {
        return price * (1 + TAX);
    }
    
    // main.js
    import { withTax } from "./math.js";
    console.log(withTax(50));
    

    Top-level variables in a module are private to that file unless exported. Modules run in strict mode and are evaluated only once, even when several files import them. In the browser, a script must be loaded with type="module", and the import path must include the file extension. Older Node.js code uses require instead.

    Worked example

    withTax(50) computes 50 × (1 + 0.2) = 50 × 1.2 = 60. TAX is exported too, but withTax uses it internally, so main.js only needs to import withTax. The output is 60.

    What you will practise

    103 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.

    Example questions

    • export makes code:
    • import brings:
    • Named exports:
    • A default export:
    • Modules help by:
    • A JavaScript module is a file that:
    • Which keyword makes a function available to other modules?
    • To load an ES module in a web page, the script tag needs:

    …and 95 more.