- String: "I am Ravi Bhadauria"
- Number: 25, 25.35, -25.36
- Boolean: true or false
- Undefined: A value that comes for top level and equal to undefined
Suppose we have a variable 'num1' with a value of '55' and another variable 'num2' with the value of 85. What will happen if we want total of the both variables.
var num1 = '55';
var num2 = 85;
So, result would be 5585 why not 140? Because num1 value type is string. You can check using typeof() operator too. So what is the solution?
alert(Number(num1) + num2); //140
In above line we have converted the num1 variable to the number and we got the desired result.
alert(parseInt(num1) + num2); //140
alert(parseFloat(num1) + num2); //140
- Unary + operator
alert((+num1) + num2); //140
- Quotes Mothod
var age = 45;
Or quote the value given to age variable like var age = '45';
Check the data type using typeof(). You will get string.
Please leave your feedbacks and suggestions in comments.
You may also like: