Use the reserved keyword
var <variable-name>; var <variable-name> = <value>;
A variable must have a unique name. The following declares a variable.
var msg; // declaring a variable without assigning a value
var msg; is a variable declaration. It does not have any value yet. The default value of variables that do not have any value is undefined.
You can assign a value to a variable using the
= operator when you declare it or after the declaration and before accessing it.
In the above example, the
msg variable is declared first and then assigned a string value in the next statement.
num variable is declared and initialized with a numeric value in the same statement.
hundred variable is declared and initialized with another variable's value.
Multiple Variables Declaration
Multiple variables can also be declared in a single line separated by a comma.
var one = 1, two = 'two', three;
White Spaces and Line Breaks in Variable Declaration
var one = 1, two = "two"
Please note that the semicolon ; at the end is optional.
C# or Java has strongly typed variables. It means a variable must be declared with the data type that specifies the type of data a variable will store.
var myvariable = 1; // numeric value myvariable = 'one'; // string value myvariable = 1.1; // decimal value myvariable = true; // Boolean value myvariable = null; // null value
Variables declared inside the function are called local variables to that function. They can only be accessed in the function where they are declared but not outside.
The following example includes global and local variables.
Declare Variables without the var Keyword
Variables can be declared and initialize without the
However, a value must be assigned to a variable declared without the
The variables declared without the
var keyword becomes global variables, irrespective of where they are declared.
It is Not Recommended to declare a variable without
var keyword because it can accidentally overwrite an existing global variable.
mSgare considered separate variables.
- Variable names can contain letters, digits, or the symbols $ and _.
- A variable name cannot start with a digit 0-9.
- Variable stores data value that can be changed later on.
- Variables can be defined using var keyword. Variables defined without var keyword become global variables.
- Variables must be initialized before accessing it.
- Multiple variables can be defined in a single line separated by a comma.
- Variable names are case-sensitive.
- Variable names can contain letters, digits, or the symbols $ and _. It cannot start with a digit 0 - 9.
- Variables can have local or global scope. Local variables cannot be accessed out of the function where they are declared, whereas the global variables can be accessed from anywhere.