gbo2600
gbo2600

Reputation: 73

How to pass the value of a variable instead of a reference into a function in Javascript

If I use the code below, the alert will say 10. I want it to say 5.

var a = 5;
var b = document.getElementById("element").onclick = ()=>alert(a);
a = 10;

How can I create an event listener that uses the value of a variable from the time it was created, rather than a reference that will change if I modify value later?

Upvotes: 2

Views: 114

Answers (1)

Barmar
Barmar

Reputation: 780949

Use an IIFE that captures the current value of a.

var a = 5;
document.getElementById("element").onclick = ((x) => ()=>alert(x))(a);
a = 10;
<button id="element">Click</button>

Upvotes: 5

Related Questions