JavaScript Variable Types |
There are different types of variables in programming classified according to the type of data they can hold. Numeric variables that can contain numeric data of various subtypes, string variables containing text data and other types.
Generally in programming languages, the type of the variable is defined when declaring the variable, and the type cannot be changed later on. In Javascript however, a variable type is not specified by user. The system guesses the variable type based on the value assigned to the variable. If a value of a different kind is assigned to the variable, javascript changes the type of the variable (treats it differently according to the new type).
The main types of variables Javascript supports
- Numeric - this can have multiple subtypes of data (described in next lesson)
- String - Text
- Logical or Boolean- True or False value.
- Objects
- Arrays
- Functions
Example
var myage = 50;
Javascript will treat the variable myage as a numeric variable due to a number in the value.
Example 2
var myname = "Leslie" ;
Javascript will treat the variable myname as a string variable due to text in the value and double quotes.
Numeric Value as string
If a number is mentioned in the value, but is given in double quotes, javascript will treat it as a string and arithmetic operations cannot be performed on that variable.
myheight = "6";
This variable is a string variable. If you add two to it, the value will not be printed as 8.
Adding up Numeric and a String Variable
If a numeric variable and a string variable are added in an expression using plus sign, Javascript converts the numeric variable into string type and concatenates(joins the text) in both the strings.
Example 1
var num1 = 5 ;
var numt = "ten";
var result = num1 + numt;
Javascript will automatically convert the variable num1 type to string and the variable result will have the value as a string "5ten";
Example 2
var num2 = 5;
var num3 = "6";
Javascript will automatically convert the variable num2 type to string and the variable result will have the value as a string "56";
To manually perform the conversion we use parseint .............................