Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Handle CORS in JavaScript ?
Next article icon

How to share code between files in JavaScript ?

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

JavaScript is a powerful and popular programming language that is widely used for web development. One of the key features of JavaScript is its ability to share code between files. This can be useful for organizing large projects, reusing code, and maintaining code quality. In this article, we'll see the different ways to share code between files in JavaScript explored.

Approaches: Below are the two different approaches for ES5 and ES6:

ES5 Approach:

  • Using 'global' variables/functions: This approach involves creating variables or functions in the global scope, which makes them accessible from anywhere in your codebase. The downside of this approach is that it can lead to naming conflicts and make it harder to keep your code organized and maintainable.
  • Using 'module.exports' and 'require' keywords: This approach is based on the CommonJS module system, which was used in Node.js. Using module.exports you can export any variable, function, or object from a file. In order to consume this exported value in another file, you use the required function to import the exported value. This approach allows you to organize your code in modules, and it is widely used for JavaScript on the server side, but in the browser environment, you will need a module bundler like webpack or Browserify.
  • Using module patterns: There are several different module patterns that can be used to share code between files in JavaScript. One popular pattern is the module revealing pattern, which is used to create a single global variable that provides access to a group of functions and variables. By using this pattern, you can organize your code and keep the global scope clean.
 

ES6 Approach:

  • Using the 'export' and 'import' keywords: This approach is based on the ECMAScript module system, a standard for JavaScript modules. The export keyword is used to export any variable, function, or object from a file, and the import keyword is used to import those exported values into another file. This approach is widely used for JavaScript on the client side, but it's also supported on the server side with tools like Node.js.
  • Using named exports and default exports: This approach allows you to export multiple values from a single file and name them individually. This way, you can import only the values that you need. It also allows you to set a default export, which can be imported without a name.
  • Combining exports from multiple files using the export * from statement: This feature allows you to import all exports from a file into a single object, which can be useful when you want to import a lot of exports from a single file.
  • Using dynamic imports with the import() function: This feature allows you to load modules dynamically at runtime, which can be useful for scenarios where you don't need all the code to be loaded at once.
  • Destructuring assignment for imports: This feature allows you to import specific variables, functions, or objects by destructuring the import statement.

As you can see, both ES5 and ES6 approaches have their own benefits and drawbacks, and it's important to understand the different options before deciding which approach to use in your application.

Example 1: Using 'global' variables/functions: A variable or function defined in the global scope (i.e., outside of any function or block), can be accessed from any file. However, it is considered a bad practice to use global data members as it might lead to naming conflicts and make code hard to read.

  •  helper.js: A file helper.js can be created as such:
JavaScript
// Defining a global function function sum(a, b) {     return a + b; }  // Defining another global function  function multiply(a, b) {     return a * b; } 
  • main.js: Then, these functions may be called in another file, main.js as follows:
JavaScript
// Function calls console.log(sum(4, 6));  console.log(multiply(4, 6));  

Output:

10  24

Example 2: Using the 'export' and 'import' Keywords: You can use the export keyword to specify which code you want to share, and then use the import keyword to access it in another file. 

  • helper.js: For example, a file helper.js can be created as such:
JavaScript
// Defining a function to be exported function sum(a, b) {     return a + b; }  // Defining another function to be exported function multiply(a, b) {     return a * b; }  // Exporting the functions export { sum, multiply }; 
  • main.js: Then, these functions may be called in another file, main.js as follows:
JavaScript
// Importing the exported functions  // from the helper.js file import { sum, multiply } from './helper.js';  // Function calls console.log(sum(4, 6));  console.log(multiply(4, 6));  

Output:

10  24

Example 3: Using module patterns: There are various patterns for organizing code in modules, such as the revealing module pattern and the Singleton pattern. These patterns can help you structure your code in a reusable way and hide implementation details.

  • helper.js: For example, a file helper.js can be created as such:
JavaScript
// Defining a Helper module const Helper = (function () {      // Defining a function to be exported     function sum(a, b) {         return a + b;     }      // Defining another function to be exported     function multiply(a, b) {         return a * b;     }      // Returning the functions     return {         sum: sum,         multiply: multiply,     }; })();  // Exporting the Helper module export default Helper; 

main.js: Then, these functions may be called in another file, main.js as follows:

JavaScript
// Importing the Helper module import Helper from './helper';  // Calling the imported functions console.log(Helper.sum(4, 6)); console.log(Helper.multiply(4, 6)); 

Output:

10  24

In conclusion, there are a number of ways to share code between files in JavaScript. The most modern and recommended approach is to use the export and import keywords, which are part of the ECMAScript module system. This allows you to specify which code you want to share and access it from other files in a clear and concise way.

Alternatively, you can use module patterns, such as the revealing module pattern or the Singleton pattern, to organize your code in a reusable way. However, these approaches can be more verbose and may require more setup. You can also use global variables to share code, but this is generally not recommended as it can lead to naming conflicts and make it harder to understand how your code works.


Next Article
How to Handle CORS in JavaScript ?

P

phasing17
Improve
Article Tags :
  • Technical Scripter
  • JavaScript
  • Web Technologies
  • Technical Scripter 2022
  • JavaScript-Questions

Similar Reads

  • How to declare namespace in JavaScript ?
    The coding standard of assigning scope to identifiers (names of types, functions, variables, and so on) to avoid conflicts between them is known as a namespace. It is a framework for a collection of identifiers, functions, and methods. It gives its contents a sense of direction so that they are easi
    3 min read
  • How to debug JavaScript File ?
    Debugging is essential because there are many errors that are not giving any kind of messages so to find out that we debug the code and find out the missing point. Example 1:  Using console.log() Method In this, we can find out the error by consoling the code in various places. Using a console is on
    2 min read
  • How to Handle CORS in JavaScript ?
    Cross-Origin Resource Sharing (CORS) is a browser-level security feature that disallows the requests (by default) to be made between different origins, i.e., a frontend client requesting a backend server that is deployed on a different origin or domain. We can bypass or allow the requests that are m
    3 min read
  • How to Upload Files in JavaScript?
    We upload files using JavaScript, for this we have to capture form elements, gather information from FormData for easier file uploads, intercept submission events, and utilize Fetch API for asynchronous server requests, for enhanced user experience and efficient data handling. ApproachProject Setup:
    1 min read
  • How To Save Text As a File in HTML CSS and JavaScript?
    In this tutorial, we will learn how to save user input as a text file using HTML, CSS, and JavaScript. This can be particularly useful for web applications where users need to download their input or notes as a file. Project PreviewWe will build a simple web page that allows users to enter text in a
    2 min read
  • How to Link JavaScript File to a Separate HTML File?
    Linking a JavaScript file to an HTML document establishes a connection between the two, allowing the execution of JavaScript code within the HTML page. This is typically done using the <script> tag in the HTML file, specifying the src attribute as the path to the JavaScript file. Below are the
    2 min read
  • JavaScript - How to Return Current URL for Share Button?
    In this article, we will learn how to create share buttons on websites, allowing users to share a post or the URL of the site on various social media platforms. We will break this down into simple steps for better understanding. Step 1: Create the HTML StructureFirst, we need to create an HTML file
    4 min read
  • Difference Between Default & Named Exports in JavaScript
    In JavaScript, exports allow you to share code between modules. There are two main types: default exports and named exports. Used to export functions, objects, or variables.Default exports allow importing with any name.Named exports require importing by the exact name.Named ExportsNamed exports let
    4 min read
  • How to define a client-side script in HTML5 ?
    To define a client-side script in HTML5, we can do <script> tag or adding external script file by src attribute to the HTML file. <script> tag contains the JavaScript to be added for the client-side scripting. Syntax: <script> // JavaScript goes here console.log('GeeksforGeeks');
    1 min read
  • How To Include a JavaScript File in Another JavaScript File?
    The import and export syntax available in ES6 (ECMAScript 2015) module is used to include a JavaScript file in another JavaScript file. This approach is the most modern and recommended way to share code between JavaScript files. It allows you to break your code into smaller modules and then import t
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences