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

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

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 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