JavaScript offers an advanced feature named modules, using these modules we can utilize
any object, class, literal, or function of one JavaScript file to any other JavaScript file. It
improves the code’s reusability and reduces the loading time of the HTML file. For this purpose,
the JavaScript modules provide two keywords, “import” and “export”Modules in JavaScript
use the import and export keywords:
• import: Used to read code exported from another module.
• export: Used to provide code to other modules.
simply write the “export” keyword prior to that variable, function, class, or anything we want to
export.
The syntax to export a variable, function, and class is:
//exporting a variable
export var emp_name;
//exporting a function
export function emp(){
}
//exporting a class
export class employee{ }
Implementation of Import in JavaScript
In JavaScript, the keyword “import” is used whenever we import anything from a file. We have to write
the “import” keyword before anything we want to import from some other file.
The syntax to import a variable, function, and class is:
//importing a variable
import {emp_name} from ‘./file name’
//importing a function
Import {emp} from ‘./file name’
//importing a class
import {employee} from ‘./file name’
Example 1: Create a file named export.js and write the below code in that file.
export let num_set = [1, 2, 3, 4, 5];
export default function hello() {
document.write("Hello World!");
export class Greeting {
constructor(name) {
this.greeting = "Hello, " + name;
Example 1: Create a file named import.html and write the below code in that file.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Import in ES6</title>
</head>
<body>
<script type="module">
// Default member first
import hello, { num_set, Greeting } from "./export.js";
document.write (num_set);
hello();
let g = new Greeting("Aakash");
document.write (g.greeting);
</script>
</body>
</html>
Example 2:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Import in ES6</title>
</head>
<body>
<script type="module">
import * as exp from "./export.js";
// Use dot notation to access members
document.write (exp.num_set);
exp.hello();
let g = new exp.Greeting("Aakash");
document.write (g.greeting);
</script>
</body>
</html>
<script type="module" src="functions.js"></script>
<script type="module" src="script.js"></script>
Example
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
document.write(person.lastName);
Example:
delete operator example
<script>
let emp = {
firstName: "Raj",
lastName: "Kumar",
salary: 40000
}
//document.write(delete emp.salary);
document.write(emp.salary);
</script>