0

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>
michael
  • 71
  • 5

1 Answers1

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.

Frank Edwards
  • 76
  • 1
  • 9
  • This is the context:I needed the global variable to use if condition in 'onkeyup' event,If 'true':do something,else:do somthing else,and the global variable solved for me this problem.(This was Before I knew the block scope was alright for replacing global variable) – michael Dec 14 '21 at 16:14