JavaScript Type Conversion
With JavaScript, a variable is defined regardless of its type. However, when assigning a value, the type of the variable is determined dynamically according to the type of the value. This means that the JavaScript language has a loose connection between the variable and the data. If we enter the initial value manually while assigning it, this will not cause a problem. However, if the value comes from a function, json or a different object, it is of great importance to check it and process it accordingly.
Let's illustrate this situation with an example.
The + (plus) symbol is used for concatenation and addition in JavaScript. If we want to perform a mathematical operation such as “5” + “10”, we need to convert the values from string to number type. Otherwise, the result will be 510 instead of 15. While explaining the subject of Javascript variables, I stated the list of types used in the JavaScript language with their explanations. After this explanation, we can convert the types we want by using the following functions to convert JavaScript types. Converting to String Type We can use one of the following two functions to convert a value to string type. value.toString() String(value)
var number=125; // typeof value -> number
var text=number.toString(); // typeof text --> string
var status=false;
var text2 =String(case);
var number=125; // typeof value -> number
var text=number.toString(); // typeof text --> string
var status=false;
var text2 =String(case);
Converting to Number Type
We can convert it to number type with the following methods. It is one of the most commonly used conversion functions. Since the values read from json, input or prompt objects are of string type, if numerical operations are to be performed, conversion must be made with the following functions.
Note: A special symbolic value NaN is created for values that are not converted to numeric values during type conversion.
//For example: When the value “10A” is wanted to be converted to a numerical value, a special value of NaN will be created.
Number(value)
parseInt(value)
parseFloat(value)
//Ex: calculating the perimeter of a rectangle whose two sides are entered
< input type="text" id="edge1" placeholder=" Short side" >
< input type="text" id="edge2" placeholder=" Long side" >
< input type="button" value="Calculate" id=" calculate" >
function calculate(){
var k1=document.getElementById("edge1").value;
var k2=document.getElementById("edge2").value;
k1=Number(k1);
k2=Number(k2);
var environment=(k1+k2)*2;
alert("The perimeter of the rectangle whose two sides are entered:"+perimeter );
}
//we select the account button for calculation.
var accountBtn=document.getElementById("calculate");
//we bind the function to the event.
accountBtn.onclick=calculate;
Converting to Boolean Type
Conversion to true/false values can be made with the Boolean function.
Boolean(value)