Using Javascript Closure to pass a variable to another function as a number

110 views Asked by At

The function below takes input from an html form

<p> How much do you want to buy?

  <input type="number" maxlength="3" name="purchase_amount" id="amount" />
  <input type="button" value="submit" onclick="get_transaction_amount(document.getElementById('amount').value)" />

</p>

The function takes the amount value and converts it to a number using parseInt. Returns a function pass_transaction_amount (for closure) that returns the cost variable

Then the make_me_a_number function creates a variable that calls the get_transaction_amount() to get the number from the closure.

function get_transaction_amount(amount) {
  let cost = parseInt(amount, 10)
  console.log(cost);
  console.log(`the type of costs is ${typeof(cost)}`)

  return function pass_transaction_amount() {
    console.log(`This is the result = ${cost}`);
    console.log(`From the return function cost is a ${typeof(cost)}`);
    return cost
  }
}

const transaction_amount = get_transaction_amount();

function make_me_a_number() {
  value = transaction_amount()
  console.log(value);
}

This does not return joy. In fact it returns NaN I realize NaN is number type but how can I get the actual amount from the closure? If I put a number in the get_transaction_amount function like this:

function get_transaction_amount(amount) {
  let cost = 10
  console.log(cost);
  console.log(`the type of costs is ${typeof(cost)}`)

  return function pass_transaction_amount() {
    console.log(`This is the result = ${cost}`);
    console.log(`From the return function cost is a ${typeof(cost)}`);
    return cost
  }
}

I do get the value, in this case 10 passed to the function make_me_a_number().

1

There are 1 answers

0
simplytrue On

Thank you again for the comments. I have found that the solution I was looking to build using the closure was not the way to solve this problem. The solution I am now going with is as follows:

First I declare a global. Then I use the function to grab the input value from the form. Then I can access the value from the global.
Its a lot cleaner then what I was trying to do...

HTML input:

<p>
    How much do you want to buy?

 <input type="number" maxlength="3" name="purchase_amount" id="amount" />
<input type="button" value="submit" onclick="get_transaction_amount(document.getElementById('amount').value)" />

</p>

javascript


/* my global */
let _AMOUNT = NaN

/* the function to get the value */

    function get_transaction_amount(amount) {
      
      let cost = parseFloat(amount, 10);

      console.log(cost);
      console.log(`the type of costs is ${typeof(cost)}`)

      _AMOUNT = cost;

    }

/* The function that can access the value from the global */

   function make_me_a_number() {

      value = _AMOUNT

      console.log(_AMOUNT);

    }

If there is a way to do it without using the global, please say.