1 of 7

JavaScript for Beginners

Day 9 : Modules

By Basavalingam

2 of 7

Course Contents

  1. Introduction to JavaScript
    1. What is Javascript?
    2. History of JavaScript
    3. What can you do with it?
    4. Where does Javascript code run?
    5. JavaScript in action!
    6. My first Javascript (Internal)!
    7. External JavaScript
    8. JavaScript Output
    9. Setting up Development Environment
    10. NodeJS in action!
  2. JavaScript Variables
  3. Statements and Code Blocks
  4. Javascript Operators and Expressions
  5. JavaScript Objects and Methods
  • JavaScript Collection Objects
    • Arrays
    • Sets
    • Maps and
    • Objects
  • Loops
  • Conditional Statements
  • Control Statements
  • JavaScript Functions
  • JavaScript Events
  • JavaScript Modules
  • JavaScript Errors
  • Math Object
  • Date Object

3 of 7

Day 9 : JavaScript Modules

4 of 7

Modules

JavaScript modules allow you to break up your code into separate files.

This makes it easier to maintain a code-base.

Modules are imported from external files with the import statement.

Modules also rely on type="module" in the <script> tag.

Note

Modules only work with the HTTP(s) protocol.

A web-page opened via the file:// protocol cannot use import / export.

5 of 7

Export

Modules with functions or variables can be stored in any external file.

There are two types of exports: Named Exports and Default Exports.

Named Exports

You can create named exports two ways. In-line individually, or all at once at the bottom.

Default Exports

You can only have one default export in a file.

person.js

//Named Export

//In-line individually

export const name = "Jesse";

export const age = 40;

//All at once at the bottom

const name = "Jesse";

const age = 40;

export {name, age};

====

message.js

//Default export

const message = () => {

const name = "Jesse";

const age = 40;

return name + ' is ' + age + 'years old.';

};

export default message;

6 of 7

Import

You can import modules into a file in two ways, based on if they are named exports or default exports.

Named exports are constructed using curly braces. Default exports are not.

//Import named exports from the file person.js

<script type="module">

import { name, age } from "./person.js";

let text = "My name is " + name + ", I am " + age + ".";

console.log(text);

</script>

Import a default export from the file message.js

<script type="module">

import message from "./message.js";

console.log(message());

</script>

7 of 7

Q&A