5+5=? Converting values to a string or number in JavaScript
In JavaScript, data can be converted automatically or using functions. In this article, we will learn how data conversion methods work in JS and why a
Let's analyze the example:
var a = 5; // number
var b = "5"; // string
var c = a + b;
alert(c); // 55
alert(typeof(c)) // string
When we add 5
and 5
, we expect to see the output — 10
. However, we get 55
and see that the data type is not a number, but a string.
JavaScript automatically converted the variable a
to a string and concatenated it with the variable b
into a single string.
To make the data type expected by the developer, use conversion functions. Let's look at them in detail.
Converting to a string in JavaScript
To convert a number to a string, use the function String()
.
For example:
var a = 5; // number
a = String(a); // convert the variable а to string
alert(typeof(a)); //string
Converting to a number in JavaScript
To convert data to a number, use the function Number()
. Let's try converting a string value 5
to a number.
var a = "5"; // string
a = Number(a); // convert the variable а to number
alert(typeof(a)); //number
If you use strings in mathematical expressions, JavaScript automatically converts variables to numbers.
For example:
var a = "5"; // string
var b = "5"; // string
var c = a / b;
alert(c);// print 1, that is expected by dividing 5 on 5
alert(typeof(c)); // number
Logical conversion to JavaScript
For logical conversion, use the function Boolean()
.
Types empty string
,NaN
, undefined
, null
— is converted to false.
All other data, such as numbers and strings, is converted to true.
For example:
var a = "null";
alert(Boolean(a)); // false
var a = "0";
alert(Boolean(a)); //true
var a = " "; // space
alert(Boolean(a)); // true
var a = ""; // empty, without spaces and other characters
alert(Boolean(a)); // false
Let's sum up the results
JavaScript can transform data automatically:
- numbers are converted to strings if they are used in expressions with a string;
- if the strings contain numbers and mathematical operations are performed with them, they are converted to numbers.
For conversion, use the functions:
String()
- converts data to numbers.Number()
- converts data to strings.Boolean()
- converts data to boolean values true or false.