Importing a JavaScript variable from one js file to another

Hi all,

I need help importing a javascript variable from one big javascript file to a script file inside an html document.

See the code snippet below:

if(total === 1)

    let probabilty = 1/2;
    let initialAmount = document.querySelector(".user-inputs").value;
    let midLevelAmount = (0.98 - probabilty)/probabilty
    let finalAmount = midLevelAmount* initialAmount;

The code above is part of a large independent JavaScript file called ‘one-in-two-functions.js’ . Now, I want to use the ‘finalAmount’ variable in a script js file which is inside an html document.

See the code below:

    <script src=""></script>
    <script src="/js/one_in_two_functions.js"></script>
    <script src="/js/one_in_two.js" ></script>
    <script src=""></script>

// I want to use the finalAmount variable in the below script file
        function handleBalance() {
            const url =

            const data = { 
                amount: document.querySelector('.user-inputs').value
            document.getElementById("checker").innerHTML = "Checking"
            const res =, data).then(resp => {
                console.log('data sent')
                document.getElementById("checker").innerHTML = "Check"
                setTimeout(function(){ window.location.reload(); }, 2000);
            }).catch(err => {

I want to use the ‘finalAmount’ variable from ‘one-in-two-functions.js’ , inside the last script tag in the html file, specifically inside the ‘handleBalance’ function.
I’m wondering how I can do that successfully. I’ve been getting errors.
Please help.

From what I can tell you are declaring finalAmount inside of an if block using let so it is only going to be available in that block of code and thus you can’t use it anywhere else. So you’ll need to declare it somewhere else so that it is available to be used outside of the if block. We’d probably need to see all of your code to give you a perfect answer.

1 Like

Hey @csibanda17,

As @bbsmooth said, you are using let to declare the function and it’s not going anywhere outside that if block. The only way to use the variable is to make a function that will return that variable then, use the function on the script file.

1 Like

Thanks guys,
You’ve pointed me in the right direction