0
0
Javascriptprogramming~5 mins

Exporting values in Javascript

Choose your learning style9 modes available
Introduction

Exporting values lets you share code like variables or functions between files. It helps keep code organized and reusable.

When you want to use a function from another file in your project.
When you have a constant value that many files need to access.
When you want to split your code into smaller, manageable parts.
When you want to share data or settings across different parts of your app.
Syntax
Javascript
export const name = value;

// or
export function myFunction() {
  // code
}

// or export multiple values
export { name1, name2 };

You can export variables, functions, or objects.

Use export before the item you want to share.

Examples
This exports a constant named pi with the value 3.14.
Javascript
export const pi = 3.14;
This exports a function named greet that prints a message.
Javascript
export function greet() {
  console.log('Hello!');
}
This exports two constants a and b together.
Javascript
const a = 1;
const b = 2;
export { a, b };
Sample Program

We export two functions add and subtract from one file. Then we import and use them in another file.

Javascript
// file: mathUtils.js
export const add = (x, y) => x + y;
export const subtract = (x, y) => x - y;

// file: main.js
import { add, subtract } from './mathUtils.js';

console.log(add(5, 3));
console.log(subtract(5, 3));
OutputSuccess
Important Notes

Remember to use import to bring exported values into another file.

File paths in import statements usually need .js extension.

Exporting helps keep code clean and easy to maintain.

Summary

Exporting shares code between files.

Use export before variables or functions you want to share.

Import exported values to use them elsewhere.