A variable can be local or global. A local variable is declared in a function using the keyword var. Variables declared without the var keyword is always global even if they are created in a function. Variables declared using the var keyword outside the functions are also global variables.
- Variable name cannot be a keyword.
- Variable name must start with a letter or an underscore followed by zero or more letters, underscores or digits.
- Variable name must not contain white spaces or punctuation marks.
- Even though use of $ sign as the beginning character of a variable name is supported by new versions of browsers, it is not recommended.
Local variables are variables that are declared within a function. The general syntax for creating a local variable is:
var variable-name = value;
The keyword var specifies that the variable is a local variable. Below are some examples for local variables:
var sum = 0; //number
var msg = “Hello”; //string
var flag = false; //boolean
var month = ”Feb”; //string
By default if no value is specified to a variable, it is treated as undefined.
A global variable is created without using the keyword var. The general syntax for creating a global variable is as shown below:
variable-name = value;
Below are some examples for global variables:
x = 1 //number
lang = “js” //string
flag = true; //boolean
If a variable is declared inside a function without using the var keyword, it is also treated as a global variable. If a variable is already declared outside the function, no new variable will be created.
The typeof operator accepts a single operand either a value or a variable and returns its type as a string value. It returns “number”, “string” and “boolean” for values or variables of the type Number, String and Boolean respectively. It returns “object” for values or variables of the type object or null. For a variable which is not assigned a value, the typeof operator returns “undefined”.
The typeof operator can be used in situations where there is a need to be absolute about the type of a value of variable before proceeding further. The typeof operator either may include parentheses for the operand or may not. So, both typeof variable and typeof(variable) are same.
Below table shows the return value of typeof operator for different values: