To define a variable, use the var
operator followed by the variable name:
var message;
This code defines a variable named message
that can hold any value.
Without initialization, it holds the special value undefined
.
We can define the variable and set its value at the same time:
var message = "hi";
Here, message
is defined to hold a string value of "hi".
Doing this initialization doesn't mark the variable as being a string type.
We can not only change the value stored in the variable but also change the type of value.
var message = "hi"; message = 100; // legal, but not recommended
In this example, the variable message
is first defined as having the string value "hi".
After that message
is overwritten with the numeric value 100.
It's not recommended to switch the data type for a variable, but it is valid in Javascript.