How to access variables from another file using JavaScript ?

26 Jul, 2021
In JavaScript, variables can be accessed from another file using the <script> tags or the import or export statement. The script tag is mainly used when we want to access variable of a JavaScript file in an HTML file. This works well for client-side scripting as well as for server-side scripting. The import or export statement however cannot be used for client-side scripting. The import or export statement works in Node.js during server-side scripting.
First Approach: At first the “module1.js” file is created and a Student object with properties “name”, “age”, “dept” and “score” is defined. The module1.js JavaScript file is imported using the src attribute of script tag within the “head” section of the HTML file. Since the JavaScript file is imported, the contents are accessible within the HTML file.
We create a button which when clicked triggers the JavaScript function. The Student object properties are accessed through the f() function and all the Student object properties are concatenated to a string variable. This string is placed within the <p> tag having ‘text’ id using the document.getElementById() and innerHTML property of HTML DOM. This is an example of a client side program.
Code Implementation:
variable_access.html
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() {            var name = Student.name;            var age = Student.age;            var dept = Student.dept;            var score = Student.score;              var 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
var Student ={    name : "ABC",    age : 18,    dept : "CSE",    score : 90};
Output:
Second Approach: In this approach, we create a JavaScript file “module1.js” and define a Student object having properties “name”, “age”, “dept” and “score”. The Student object is exported using module.exports. In another JavaScript module file “module2.js“, we import “module1.js” using the import statement at the beginning of the file. The objects Hostel and Hostel_Allocation are defined in “module2.js” file and the Student object is accessed in the Hostel_Allocation object.
A HTTP server is created and hosted at port no. 8080. The properties of Hostel_Allocation are concatenated in a string. This string is printed on the landing page of the web application whenever it is run. This is an example of server side scripting.
Code Implementation:
module1.js
Javascript
var Student = {    name : "ABC",    age : 18,    dept : "CSE",    score : 90};module.exports = {Student};
module2.js
Javascript
var http = require('http');const {Student} = require('./module1.js');  var Hostel = {    student_count: 500,    no_of_rooms: 250,    hostel_fees: 12000}  var Hostel_Allocation = {    room_no : 151,    student_name: Student.name,    student_age: Student.age,    student_dept: Student.dept,    total_fees: 12000}  var 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
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.
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.