Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

261
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda