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

344
Views
Can we use javascript variables which are defined in callback functions, outside of it(callback function)?

This is my code.

var scoreResults = document.querySelectorAll(".flex-blackjack-row-1 h3");
var scores = document.querySelector(".flex-blackjack-row-1 span");

const config = {childList: true};

const busted = function (mutationList, observer){
    
        var bustedMessage = document.createElement('h2');
        bustedMessage.textContent = 'BUSTED!';
        scoreResults[0].before(bustedMessage);
        hitButton.setAttribute('disabled', 'true');
    
}

const observer = new MutationObserver(busted);
observer.observe(scores, config);

I have defined bustedMessage variable in a callback function and I want to use it outside of that callback function. Still after successfully invoking the busted function (that means still after initiating the bustedMessage variable ), that variable can not be used outside of the callback function.

But when I take out this code block,

    var bustedMessage = document.createElement('h2');
    bustedMessage.textContent = 'BUSTED!';

to the outside from "busted" callback function, I can use bustedMessage variable in other functions too. Please explain why is this happening? I can not understand it because bustedMessage is a var type variable which is ought to use in anywhere.

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

0

Define bustedMessage outside first

var bustedMessage;

const busted = function (mutationList, observer){
    
        bustedMessage = document.createElement('h2');
        bustedMessage.textContent = 'BUSTED!';
        scoreResults[0].before(bustedMessage);
        hitButton.setAttribute('disabled', 'true');
    
}

you are now free to use bustedMessage anywhere in this script, of course it's undefined until you call busted for the first time.

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!