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

188
Visualizações
Block scope in relation to global variables

Assuming I need to use global variable for some script:(example)

<script>
let myVAR=0;
// some functions
......
......
</script>

Is the following code good for preventing use of global variable? (for my understanding,this is called Block scope,If I'm wrong please clarify me). Second,Is this bad practice or it's not? If it is,Is there another method to replace global variable?(My target is to access multiple functions in the script with unknown amount of uses,with onclick events,onkeyup events,etc..)

<script>
{
let myVAR=0;
// some functions
......
......
}
</script>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Well, I would like to start off with saying that you should avoid using global variables whenever possible, and if the value doesn't need to change then you should declare it with const instead.

It can be kind of tricky when you are new, but it is much better to write your functions to accept a parameter, and to pass that variable to the function itself.

Here's an example:

function multiplyTwoNumbers((num1, num2) => {
    const product = num1 * num2;
    return product
})

function addTwoNumbers((num1, num2) => {
    const sum = num1 + num2;
    return sum
})

function calculateNumbers(() => {
    const num1 = 5;
    const num2 = 3;

    const product = multiplyTwoNumbers(num1, 
         num2);
    const sum = addTwoNumbers(num1, num2);

    console.log(product, sum)
})

Now do note, this is just a basic example, and there are multiple ways to achieve a similar affect.

If you are able to provide more context, I would be happy to provide a more relevant example for you.

Edit: Forgot to add, you should also avoid writing inline Javascript in the script tag. It's better to have an external javascript file, and to link the script in the html file.

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