Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

265
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda