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

263
Views
how to use local variable of function outside of that function in javascript

hi everyone I'm facing difficulty while using a local variable of a function outside of it, is there any way to do that.

instance.onmessage = (e) => {
  let color = e.data
  return color;
};

I'm getting color from instance.onmessage and I have to use this color in the code below.

visualLinks.lineStyle(
 2,
 link.edgeType === value ? 0xff0000 : color
);

instance.onmessage = (e) => {
   let color=e.data
   return color;
};

visualLinks.lineStyle(
  2,
  link.edgeType === value ? 0xff0000 : color
);

I know that this is wrong but I have to perform something like this for reference only, I wrote this code.

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

0

You can't use a local variable of a function outside of that function in JavaScript. You could make it a global variable instead:

let color = undefined;
window.onmessage = (e) => {
  color = e.data
};

// THIS WILL NOT WORK (because color is still undefined)
console.log(color);
visualLinks.lineStyle(
  2,
  link.edgeType === value ? 0xff0000 : color
);

In the case of your code which uses onmessage(), your onmessage callback function won't have been run (your function doesn't run until a message is received) in time for any code right after it.

You could wait to run that code until the message is received by moving it inside of the function.

let color = undefined;
window.onmessage = (e) => {
  color = e.data;
  console.log(color);
  visualLinks.lineStyle(
    2,
    link.edgeType === value ? 0xff0000 : color
  );
};

If this is too simple an answer to be useful, you may have better luck if you include a more realistic example of what you're trying to do.

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!