JavaScript is a loosely typed programming language. It does not mean that it has no data types or very few data types, but the value of a variable or an object can hold any value irrespective of its data type. JavaScript automatically type converts a variable into a suitable data type based on requirement and situation.
Even though JavaScript is loosely typed and automatically type converts, it is the programmer’s responsibility to note the actual data type of a variables and deal with them accordingly.
For example, often working with value of a input from form control where a user types a number value and a script will add that number with another number. The value of a form control is always a string and an attempt to add that value with another number results in string concatenation instead of a number addition.
The problem is because dual nature of + operator as it is used for addition as well as string concatenation. If both operands are number than addition is performed otherwise string concatenation is performed
In JavaScript type conversion can be done two ways
String() method is used to convert a number, boolean or date to string type.
<!DOCTYPE html>
<html>
<body>
String() method is used to convert to variable, value or expression to String type.
<p id="text"></p>
<script>
var num=10;
document.getElementById("text").innerHTML =
String(num) + "<br>" +
String(10) + "<br>" +
String(10 * 10) + "<br>" +
String(false) + "<br>" +
String(true) + "<br>" +
String(Date());
</script>
</body>
</html>
toString() method can be used for same purpose
<!DOCTYPE html>
<html>
<body>
toString() method is used to convert a variable, value or expression to String type.
<p id="text"></p>
<script>
var num=10;
document.getElementById("text").innerHTML =
num.toString() + "<br>" +
(10).toString() + "<br>" +
(10 * 10).toString() + "<br>" +
(true).toString() + "<br>" +
(false).toString() + "<br>" +
(Date()).toString();
</script>
</body>
</html>
Number() method is used to convert string to number.
Empty string converted to 0 and string with decimal point converted to floating point number and all other values converted to NaN values.
<!DOCTYPE html>
<html>
<body>
Number() method is used to convert a variable, value or expression to number type.
<p id="text"></p>
<script>
var num=10;
document.getElementById("text").innerHTML =
Number("1.99") + '<br />' +
Number("") + '<br />' +
Number(" ") + '<br />' +
Number(true) + '<br />' +
Number(false) + '<br />' +
Number(new Date()) + '<br />' +
Number("1 2 3 4 5");
</script>
</body>
</html>
When JavaScript variable is used in expression, it is automatically converted to its appropriate type.
<!DOCTYPE html>
<html>
<body>
Number() method is used to convert a variable, value or expression to number type.
<p id="text"></p>
<script>
var num=10;
document.getElementById("text").innerHTML =
(10 + null) + '<br />' +
(null + 10) + '<br />' +
("10" + null) + '<br />' +
("10" + 10) + '<br />' +
("10" - 10);
</script>
</body>
</html>