0
0
Javascriptprogramming~5 mins

Module scope in Javascript

Choose your learning style9 modes available
Introduction

Module scope keeps variables and functions private inside a file. This helps avoid mixing up names and keeps code organized.

When you want to keep helper functions hidden from other parts of your program.
When you want to share only specific parts of your code with other files.
When you want to avoid name conflicts between variables in different files.
When building bigger projects with many files to keep code clean and safe.
Syntax
Javascript
export const publicValue = 42;

const privateValue = 10;

function privateFunction() {
  return privateValue;
}

export function publicFunction() {
  return privateFunction() + publicValue;
}

Variables and functions not exported stay private to the module.

Use export keyword to share parts of the module.

Examples
secret is private, visible is public and can be used in other files.
Javascript
const secret = 'hidden';

export const visible = 'shown';
helper is private, only main is exported.
Javascript
function helper() {
  return 5;
}

export function main() {
  return helper() * 2;
}
Sample Program

In mathModule.js, secretNumber is private. Only addFive is exported and used in app.js.

Javascript
// file: mathModule.js
const secretNumber = 7;

export function addFive(num) {
  return num + secretNumber;
}

// file: app.js
import { addFive } from './mathModule.js';

console.log(addFive(3));
OutputSuccess
Important Notes

Each JavaScript file is a module with its own scope by default when using ES modules.

Variables not exported cannot be accessed from other files.

Use import to bring exported parts into another module.

Summary

Module scope keeps code private inside files.

Use export to share code outside the module.

Helps avoid name conflicts and keeps code organized.