In the above example, the variable userName becomes a global variable because it is declared outside of any function. A modifyUserName() function modifies userName as userName is a global variable and can be accessed inside any function. The same way, showUserName() function displays current value of userName variable. Changing value of global variable in any function will reflect throughout the program.

Please note that variables declared inside a function without var keyword also become global variables.

In the above example, variable userName is declared without var keyword inside createUserName(), so it becomes global variable automatically after calling createUserName() for the first time.

Note :
A userName variable will become global variable only after createUserName() is called at least once. Calling showUserName() before createUserName() will throw an exception "userName is not defined".

Local scope:

Variables declared inside any function with var keyword are called local variables. Local variables cannot be accessed or modified outside the function declaration.

In the above example, userName is local to createUserName() function. It cannot be accessed in showUserName() function or any other functions. It will throw an error if you try to access a variable which is not in the local or global scope. Use try catch block for exception handling.

Some tips..

If local variable and global variable have same name then changing value of one variable does not affect on the value of another variable.