Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!