Functions and modules
ECMAScript 2026
A function gives a piece of work a name so you can run it again with different inputs. A module is a file that can share selected definitions with other files.
On this page
Define and call a function
function introduces reusable code. The name is followed by parentheses and a block. Defining a function makes it available. Writing its name followed by () calls it and runs the block.
How to try it Open a browser tab, then open Developer Tools → Console. Type the example or paste it into the Console after reviewing it, then run it. Reload before repeating declarations with the same names.
function sayReady() {
console.log("Your order is ready.");
}
sayReady();
sayReady();
What to expect The same message appears twice because the function is called twice.
Pass inputs and return a result
A parameter is a name for an input inside a function. An argument is a value you pass when calling it. A default parameter supplies a value when that argument is omitted or undefined. return ends the call and sends the result back to its caller.
How to try it Open a browser tab, then open Developer Tools → Console. Type the example or paste it into the Console after reviewing it, then run it. Reload before repeating declarations with the same names.
function total(price, quantity = 1) {
return price * quantity;
}
console.log(total(2500), total(2500, 2));
What to expect The first call returns 2500 and the second returns 5000.
Share a function with export
An export marks a definition the module makes available to another module. Here total is a named export. Code using it can import that same name.
How to try it Create an empty folder, then save this as total.js in it.
export function total(price, quantity = 1) {
return price * quantity;
}
What to expect The file now makes total available to the importing module. The result appears after running the next example.
Import and run a browser module
import names what you want to use and tells the browser where the module is. ./ means the same folder. A script with type="module" allows import in that script. Serve the page over HTTP so both files are loaded from the same origin.
How to try it Save as index.html beside total.js. In VS Code, open that folder and use a local server such as Live Server. With Python installed, you can also run python -m http.server 8000 in the folder and open http://localhost:8000.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Module demo</title>
</head>
<body>
<p>Open the Console to see the total.</p>
<script type="module">
import { total } from "./total.js";
console.log(total(2500, 2));
</script>
</body>
</html>
What to expect The Console prints 5000 when the browser loads the module.