There are two types of Variables in JavaScript :
- Local Variables
- Global Variables
Local Variable :
- Variable declared inside JavaScript Function will become “local Variable“.
- Local variable is visible inside the function in which it is declared.
- Other Function cannot access local variable declared in another function.
- Local Variables are destroyed after execution of function.
<html> <head> <script type="text/javascript"> function message() { var name="Pritesh"; alert(name); } </script> </head> <body> <form> <input type="button" value="Click me!" onclick="message()" /> </form> </body> </html>
Global Variable :
- Variable declared outside JavaScript Function will become “Global Variable“.
- All Scripts and JavaScript Functions can access Global Variables.
- When User closes browser global variable is destroyed.
- Variables declared without using “var keyword” will be considered as Global Variable.
<html> <body> <script type="text/javascript"> var name; name="Pritesh"; </script> <script type="text/javascript"> document.write(name); </script> <p>Global Variable Can be accessed from other Script</p> </body> </html>
Difference between Global Variable and Local Variable
Parameter | Global Variable | Local Variable |
---|---|---|
Scope | All JavaScript Functions and Scripts | Function in which it is declared |
Destroyed When | User Closes browser | After Execution of function |
Can we declare same variable again | Not possible | Possible but outside function in which it is declared |