client-side program

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 the 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 that 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.

Example: In this example, we are following the above approach.

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:

How to access variables from another file using JavaScript ?

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 a 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.

Below are the approaches for both server and client side:

Table of Content

  • client-side program
  • server-side scripting

Similar Reads

Approach 1: client-side program

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 the script tag within the “head” section of the HTML file. Since the JavaScript file is imported, the contents are accessible within the HTML file....

Approach 2: Server-side scripting

...

Contact Us