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

122
Views
Call a function inside a function and return a value

Is it possible to call a function on click a button, execute some code like adding an item to a database and also having access to a variable that was created in that function?

For example,

const handleAddToDb = () => {
  let id = 123423r //note the ID is auto generated each time this function is called
   addToDb()
   return id
}
<button onClick={()=> {
  handleAddToDb()
}}>Click</button>
console.log(id???) //any idea how to acheive this?
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

<body>
    <button onclick="
            handleAddToDb()
    ">
    Click me
    </button>
</body>
<script>
    // let id is a global variable
    let id = 10;
    const handleAddToDb = () => {
        addToDb()
        console.log(id)
    }
    function addToDb(){
        id++;
    }
    console.log(id) //any idea how to acheive this?
</script>

about 4 years ago · Juan Pablo Isaza Report

0

You could have your click handler return the id (as you're doing) and assign it to a variable that's accessible in your outer scope.

You could also establish a "store" that's responsible for managing all of the data, including doing the add and keeping track of the new id. See snippet below for a very skeletal example of how two separate buttons can access the same data using this approach.

const addButton = document.getElementById('add');
const logButton = document.getElementById('log');

class Store {
  lastId = 0;
  
  add() {
    // do whatever you need to do.
    // increment and return the id.
    return this.lastId++;
  }
}

const store = new Store();

addButton.addEventListener('click', () => {
  store.add();
  console.log(store.lastId);
})

logButton.addEventListener('click', () => {
  console.log(store.lastId);
})
<button id="add">Add</button>

<button id="log">Log Last Id</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!