Back to JavaScript
2026-05-018 min read

3. Using the filename only (JavaScript)

Learn 3. Using the filename only (JavaScript) step by step with clear examples and exercises.

Why This Matters

Before diving into the core concept of using filenames effectively in JavaScript, it's essential to have a basic understanding of:

  1. JavaScript syntax and variables
  2. Basic file handling (creating, reading, writing, and deleting files) in your operating system
  3. HTML structure and how to include JavaScript files in an HTML document
  4. Understanding the difference between regular JavaScript files and ES6 modules
  5. Familiarity with importing and exporting functions or classes in ES6 modules
  6. Basic knowledge of Node.js and CommonJS modules (for server-side JavaScript)

Prerequisites

To follow along with this lesson, you should have a good understanding of:

  1. JavaScript basics, including variables, data types, operators, functions, and control structures
  2. HTML structure and how to create, read, write, and delete files using JavaScript in your operating system (e.g., Node.js for server-side JavaScript)
  3. Basic concepts of ES6 modules and CommonJS modules

Core Concept

The core concept revolves around naming conventions, file organization, and the use of JavaScript modules to manage dependencies effectively.

File Naming Rules

JavaScript filenames follow the same naming conventions as other files on your computer. They can contain letters (a-z, A-Z), numbers (0-9), underscores (_), and hyphens (-). However, it's recommended to use only lowercase letters and avoid special characters.

JavaScript filenames should be descriptive and easy to understand. For example, a script that handles user registration could be named user_registration.js.

Including JavaScript Files in HTML

To include a JavaScript file in an HTML document, you can use the ` tag with the src` attribute:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My JavaScript Project</title>
</head>
<body>
<!-- Your HTML content here -->

<!-- Include the JavaScript file -->
<script src="scripts/user_registration.js"></script>
</body>
</html>

In this example, the user_registration.js file should be located in a folder named scripts.

Importing JavaScript Modules (ES6)

Modern JavaScript projects often use modules to organize code and manage dependencies. To import a module, you can use the import statement:

// user_registration.mjs (ES6 Module)
export function registerUser(user) {
// Registration logic here
}

// main.mjs (ES6 Module)
import { registerUser } from './user_registration.mjs';

registerUser({ name: 'John Doe', email: 'john@example.com' });

In this example, the user_registration.mjs file exports a function called registerUser, which can be imported and used in another JavaScript module (main.mjs).

Using CommonJS Modules (Node.js)

When working with Node.js, you might encounter CommonJS modules. To create a CommonJS module, save your file with the .js extension instead of .mjs, and use the module.exports object to export functions or objects:

// user_registration.js (CommonJS Module)
module.exports = {
registerUser: function(user) {
// Registration logic here
}
};

// main.js (CommonJS Module)
var userRegistration = require('./user_registration');
userRegistration.registerUser({ name: 'John Doe', email: 'john@example.com' });

In this example, the user_registration.js file exports an object that includes a registerUser function, which can be imported and used in another JavaScript module (main.js) using the require() function.

Worked Example

Let's create a simple project with two files: index.html and app.mjs. The index.html file will include the app.mjs file, and app.mjs will define a function that logs a message to the console.

  1. Create an empty folder for your project (e.g., my_project).
  2. Inside the folder, create two files: index.html and app.mjs.
  3. Open index.html in a text editor and add the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My JavaScript Project</title>
</head>
<body>
<!-- Your HTML content here -->

<!-- Include the JavaScript file -->
<script type="module" src="app.mjs"></script>
</body>
</html>
  1. Open app.mjs in a text editor and add the following content:
// app.mjs (ES6 Module)
export function logMessage(message) {
console.log(message);
}

logMessage('Hello, World!');
  1. Save both files and open index.html in a web browser that supports ES6 modules (e.g., Google Chrome or Firefox). You should see "Hello, World!" displayed in the console.

Worked Example - Expanded

To demonstrate the power of using JavaScript modules effectively, let's expand our previous example by creating separate files for different functionalities:

  1. Create an empty folder for your project (e.g., my_project).
  2. Inside the folder, create three files: index.html, app.mjs, and user_registration.mjs.
  3. Open user_registration.mjs in a text editor and add the following content:
// user_registration.mjs (ES6 Module)
export function registerUser(user) {
const users = [];
users.push(user);
console.log(`Registered user: ${JSON.stringify(user)}`);
}
  1. Open app.mjs in a text editor and add the following content:
// app.mjs (ES6 Module)
import { registerUser } from './user_registration.mjs';

registerUser({ name: 'John Doe', email: 'john@example.com' });
registerUser({ name: 'Jane Smith', email: 'jane@example.com' });
  1. Open index.html in a text editor and add the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My JavaScript Project</title>
</head>
<body>
<!-- Your HTML content here -->

<!-- Include the JavaScript file -->
<script type="module" src="app.mjs"></script>
</body>
</html>
  1. Save both files and open index.html in a web browser that supports ES6 modules (e.g., Google Chrome or Firefox). You should see the following output in the console:
Registered user: {"name":"John Doe","email":"john@example.com"}
Registered user: {"name":"Jane Smith","email":"jane@example.com"}

Common Mistakes

  1. Incorrect file extension: Make sure your JavaScript files have the appropriate file extension (.js for CommonJS and .mjs for ES6 modules) if you're using modern JavaScript features like modules.
  2. Incorrect path to the JavaScript file: Ensure that the path to the JavaScript file in the HTML `` tag is correct and relative to the HTML file.
  3. Case sensitivity: Be aware that filenames are case-sensitive, so make sure your filenames match exactly when you reference them in your HTML or other JavaScript files.
  4. Forgetting to include the JavaScript file: Don't forget to include the JavaScript file in your HTML document using the `` tag.
  5. Not defining functions as exported modules (if applicable): In modern JavaScript projects, make sure you define functions as exported modules if you plan on importing them in other files.
  6. Incorrectly using CommonJS and ES6 modules together: When working with Node.js, ensure that all your modules use either CommonJS or ES6 syntax consistently within the same project. Mixing the two can cause issues.
  7. Missing type="module" attribute in HTML file: Include the type="module" attribute when using ES6 modules in an HTML file to prevent browser compatibility issues.
  8. Not handling errors properly: Make sure to handle errors gracefully, especially when working with user input or external APIs.
  9. Ignoring best practices for code organization and readability: Keep your code organized, easy to understand, and follow common conventions like using descriptive variable names, comments, and consistent indentation.
  10. Not optimizing performance: Be aware of potential performance issues, such as excessive memory usage or slow functions, and take steps to optimize your code where necessary.

Practice Questions

  1. Rewrite the example project to handle user registration and log the registered users in a file named users.txt.
  2. Create a simple calculator application with two JavaScript files: one for handling user input, and another for performing calculations and displaying results. Use ES6 modules.
  3. Write a JavaScript function that checks if a given filename is valid (follows naming conventions). This function should return true if the filename follows the rules and false otherwise.
  4. Write a script that creates a simple web server using Node.js to serve HTML files and JavaScript modules. The user should be able to navigate between multiple pages, each with its own JavaScript module.
  5. Create a JavaScript library for handling common form validations (e.g., email, password strength). Use ES6 modules and export functions that can be imported by other projects.

FAQ

Q1: Can I use spaces in my JavaScript filenames?

A1: While it's technically possible, it's not recommended because spaces can cause issues when working with the file system or including the file in an HTML document. Instead, use underscores (_) or hyphens (-) to separate words in your filenames.

Q2: How do I include multiple JavaScript files in an HTML document?

A2: You can include multiple JavaScript files by adding multiple ` tags with the src attribute for each file. Make sure to include them in the correct order, as the order matters if there are dependencies between the files. If you're using ES6 modules, use the type="module" attribute and import the required modules using the import` statement.

Q3: What is the difference between a JavaScript module and a regular JavaScript file?

A3: A JavaScript module is a self-contained unit of code that can be imported and used in other modules or scripts. Regular JavaScript files can also be included in HTML documents, but they don't have the same modular structure as ES6 modules. Modern JavaScript projects often use modules to organize code and manage dependencies more effectively.

Q4: How do I handle naming conflicts between imported modules?

A4: To avoid naming conflicts when importing multiple modules with the same function or variable name, you can rename the conflicting items in one of the modules or use a different syntax to access them. For example, you could use destructuring assignments (ES6) to selectively import specific functions or variables from a module.

Q5: How do I handle dependencies between JavaScript modules?

A5: To manage dependencies between JavaScript modules, you can create a dependency graph and install the required packages using a package manager like npm for Node.js projects. This ensures that all the necessary modules are available when your code runs.

Q6: Can I use both CommonJS and ES6 modules in the same project?

A6: Yes, you can use both CommonJS and ES6 modules in the same project by using a module bundler like Webpack or Rollup. These tools convert multiple JavaScript modules into a single file that can be included in an HTML document or executed on the server with Node.js.

Q7: How do I create a reusable JavaScript library?

A7: To create a reusable JavaScript library, follow these steps:

  1. Organize your code into separate modules for different functionalities.
  2. Use descriptive and consistent naming conventions for your modules, functions, and variables.
  3. Write comprehensive documentation explaining how to use your library, including examples and potential pitfalls.
  4. Publish your library on a package repository like npm or GitHub so that others can easily find and use it in their projects.
3. Using the filename only (JavaScript) | JavaScript | XQA Learn