0

say I have a

function value(num) {
  var numHolder = [];
  numHolder.push(num);
  console.log(num);
}

and I have button with different numbers each invoking the function with different arguments of each button. for example, number 1 button will invoke as

onclick="value(1)" 

number 2 button will invoke as

onclick="value(2)"

how can I save these values inside the numHolder array without making the numHolder array global?

1 Answer 1

2

Use an IIFE to create a closure

// `value` is initialised but undefined here (can be referenced because of `var`)
// ..
var value = (function (numHolder) { // IIFE creating closure
    return function (num) { // function expression to be assigned to `value`
        numHolder.push(num);
        console.log(num);
        // `numHolder` accessible here
    };
    // `numHolder` accessible here
}([])); // initial value for `numHolder`
// `value` is fully defined here
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.