This article discusses about the data and data types or value and value types in JavaScript. JavaScript recognizes 5 following given values.
Values in JavaScript
- String: “I am Ravi Bhadauria”
- Number: 25, 25.35, -25.36
- Boolean: true or false
- null: It is a special keyword in JavaScript denotes to a null value
- Undefined: A value that comes for top level and equal to undefined
Value or Data Types in JavaScript
JavaScript introduces 5 primitive data types too for the respective above given values or data.
- string
- number
- boolean
- null
- undefined
Data Type Conversion or Type Casting in JavaScript
All we know that JavaScript is a dynamic type language; meaning we don’t need to explicitly declare data types of the variables. It converts them automatically. JavaScript offers various functions to deal with data type conversion process. Here I will discuss few of the common ways to deal with data type conversion in JavaScript.
Converting a String to Number in JavaScript
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.
Example:
var num1 = ’55’;
var num2 = 85;
alert(num1+num2); //5585
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.
We have some other functions to convert a string value to the number in JavaScript.
- Number()
- parseInt()
alert(parseInt(num1) + num2); //140 - parseFloat()
alert(parseFloat(num1) + num2); //140 - Unary + operator
alert((+num1) + num2); //140
Number to String Conversion in JavaScript
There are various ways to do it in JavaScript. But I am explaining one of the easiest methods here.
- String()
- toString()
- Quotes Mothod
Example:
var age = 45;
String(age);
or
age.toString();
Or quote the value given to age variable like var age = ’45’;
Check the data type using typeof(). You will get string.
Hope this will help someone in knowing JavaScript’s data types.
Please leave your feedbacks and suggestions in comments.
Thanks