The variables you declare can be global or local.
If you declare a variable outside of any function definition, it is a global variable. It lives for as long as your application lives. Any part of your program can access the global variable and change its value.
Variables created inside functions with the keyword var are local. Local variables have short lives: they come into existence when the function is invoked, and disappear when the function exits. The local variable can only be used and its value modified inside of a function declaring it.
A global and a local variable with the same name can coexist. They are in every way two different variables and modifying one does not affect the other. Here is an example:
str = "This is a global string";
var str = "This is a local string";
Points to remember:
Global variables can be accessed by other variables and functions.
Local variables can be accessed only within the function declaring them.
Variables declared inside a function without the keyword var are global.
When declared inside a function with the keyword var, the variable is local to the function declaring it.
Declaring a variable outside of a function makes it global.