- Local Variable:
- Global Variable:
In contrast, global variables are variables that are defined outside of functions. These variables have global scope, so they can be used by any function without passing them to the function as parameters.
- Although it may seem easier to use global variables than to pass data to a function and return data from it, global variables often create problems. That’s because any function can modify a global variable, and it’s all too easy to misspell a variable name or modify the wrong variable, especially in large applications. That, in turn, can create debugging problems.
- In contrast, the use of local variables reduces the likelihood of naming conflicts. For instance, two different functions can use the same names for local variables without causing conflicts. That of course, means fewer errors and debugging problems. With just a few exceptions, then, all of the code in your applications should be in functions so all of the variables are local.
- If you misspell the name of a variable that you’ve already declared, it will be treated as a new global variable. With this in mind, be sure to include the keyword when you declare new variables and always declare a variable before you refer to it in your code.
- The scope of a variable or function determines what code has access to it.
- Variables that are created inside a function are local variables, and local variables, and local variables can only be referred to by the code within the function.
- Variables created outside of functions are global variables, and the code in all functions have access to all global variables.
- In general, it’s better to pass local variables from one function to another as parameters than it is to use global variables. That will make your code easier to understand with less chance for errors.
Local Variable: Since local variables are defined inside the function so variables with the same name can be used in different functions.
The above example illustrates the use of a local variable. However, that a statement outside of the function can’t refer to the variable named petName without causing an error. That’s because it has local scope.
Global Variable: Since global variables are defined outside there function so variables with the same name can not be used in different functions. All the scripts and functions on a web page can access it.
Where to use which variables:
Note: Use local variables whenever possible.Always use the var keyword to declare a new variable before the variable is referred to by other statements.
- How to use variables: