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

187
Views
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 answers
Answer question

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