How to Access Variables from Another File using JavaScript?
Last Updated :
09 Sep, 2024
Accessing variables from another file in JavaScript involves exporting the variables from one file and importing them into another. In ES6 modules, use export to share variables and import to access them. In CommonJS (Node.js), use module.exports and require() for the same purpose.
Below are the approaches for both server and client side:
Client-side program
First, create module1.js with a Student object containing properties like name, age, dept, and score. Import this file in the HTML <head> using the src attribute of the <script> tag. A button triggers a function that accesses and displays these properties in a <p> tag.
Example: In this example, we displays student details when a button is clicked. The JavaScript function f() retrieves data from a Student object and updates the content of a <p> element.
HTML
<!-- variable_access.html -->
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="module1.js">
</script>
</head>
<body>
<button onclick="f()">
Click Me To Get Student Details
</button>
<div>
<p id="text" style="color:purple;
font-weight:bold;font-size:20px;">
</p>
</div>
<script type="text/javascript">
function f() {
let name = Student.name;
let age = Student.age;
let dept = Student.dept;
let score = Student.score;
let str = "Name:" + name + "\nAge: "
+ age + "\nDepartment:" + dept
+ "\nScore: " + score;
document.getElementById(
'text').innerHTML = str;
}
</script>
</body>
</html>
module1.js This file is used in the above HTML code.
JavaScript
//module1.js
let Student =
{
name: "ABC",
age: 18,
dept: "CSE",
score: 90
};
Output:

Server-side scripting
In this approach, module1.js defines and exports a Student object. module2.js imports it, defines Hostel and Hostel_Allocation objects, and accesses the Student object. An HTTP server on port 8080 displays concatenated Hostel_Allocation properties on the web application's landing page.
Example: In this example, we are following the above approach.
module1.js
JavaScript
//module1.js
let Student = {
name : "ABC",
age : 18,
dept : "CSE",
score : 90
};
module.exports = {Student};
module2.js
JavaScript
// module2.js
let http = require('http');
const { Student } = require('./module1.js');
let Hostel = {
student_count: 500,
no_of_rooms: 250,
hostel_fees: 12000
}
let Hostel_Allocation = {
room_no: 151,
student_name: Student.name,
student_age: Student.age,
student_dept: Student.dept,
total_fees: 12000
}
let str = "Room No: " + Hostel_Allocation.room_no
+ "\nStudent Name: "
+ Hostel_Allocation.student_name
+ "\nTotal Fees: "
+ Hostel_Allocation.total_fees;
http.createServer(function (req, res) {
res.write(str);
res.end();
}).listen(8080);
Output:
Start the server
node module2.js
Run the application in the browser
localhost:8080
Output:
Room No: 151
Student Name : ABC
Total Fees : 12000
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Similar Reads
How to Access EJS Variable in Javascript Logic ? EJS stands for Embedded JavaScript. It is a templating language used to generate dynamic HTML pages with data from the server by embedding JavaScript code. Features of EJSDynamic Content: Based on data from servers or other sources, we can generate a dynamic HTML template.Partial Templates: Partials
3 min read
How to declare Global Variables in JavaScript ? Global Variables Global variables in JavaScript are variables declared outside of any function. These variables are accessible from anywhere within the script, including inside functions. Global variables are declared at the start of the block(top of the program)Var keyword is used to declare variab
2 min read
How to Display JavaScript Variable Value in Alert Box ? An alert box is a dialog box that pops up on the screen to provide information to the user. It contains a message and an OK button, which allow users to acknowledge the message and close the box. Alert boxes are commonly used in web development to display important messages, warnings, or notificatio
2 min read
How to make .js variables accessible to .ejs files ? EJS is a simple templating language that lets you generate HTML markup with plain JavaScript. It is possible to access JS variable in .ejs file.You just need to pass the JS object as second parameter of res.render() method. Let's jump into deep. Project Structure: Final folder structure will be as s
3 min read
How to Pass/Access Node.js Variable to an HTML file/template ? When building web applications with Node.js, itâs often necessary to pass server-side variables to the client-side for rendering dynamic content. This can be achieved using various techniques and templating engines. This article will guide you through different methods to pass and access Node.js var
2 min read
View the list of all variables in Google Chrome Console using JavaScript All the variables in Google Chrome can be listed for the use of debugging. There are two approaches to list all variables: Method 1: Iterating through properties of the window object: The window object in JavaScript represents the current browser's window. The properties of this object can be used t
2 min read
How to create a private variable in JavaScript ? In this article, we will try to understand how we could create private variables in JavaScript. Let us first understand what are the ways through which we may declare the variables generally in JavaScript. Syntax: By using the following syntaxes we could declare our variables in JavaScript. var vari
3 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 th
4 min read
How to pass Variable to inline JavaScript using EJS Template Engine? In the EJS templating engine, we can pass variables to inline JS within our HTML templates. We can use the '<%= variable %>' syntax, where we can embed server-side variables directly into the client-side scripts. In this article, we will explore the detailed process to pass a variable to inlin
2 min read