The following command line defines two different variables and prints them;
var num = 4; var str = "I am a string!"; document.write("The string is: " + str,"<br/>"); document.write("The number is: " + num,"<br/>");
However, since the data type is unknown, depending on the mathematical operation (summation, multiplication, etc. ) JS acts different than most of the programming languages. The following example defines 4 different variables and some mathematical operations done with them;
var num = 5; var num2 = 9; var str = "3"; var str2 = "16"; document.write("Summation: " + num + str,"<br/>"); document.write("Multiplication: " + num * str,"<br/>"); // Correct Summation and Multiplication document.write("Correct Summation: " + Number(num + Number(str)),"<br/>"); document.write("Multiplication: " + num * Number(str),"<br/>"); // Concatenation Operation = 9 + "16" = 916 document.write("Concatenation: " + String(num2) + str2,"<br/>");
Fist of all, the reason that the first summation fails is because if we are doing a summation with a string and an integer, JS converts the integer to a string and concatenates them. On the other hand, when we are doing a multiplication, the string is converted to an integer and therefore both Multiplication operations gave the same results in the example above. In order to perform correct summation and concatenation Number( ) and String( ) functions should be used.
Now let's further look into some other useful functions of JS such as toFixed( ), parseInt( ) and typeof( ).
var num3 = 3.98478532; document.write("toFixed Output: " + num3.toFixed(4),"<br/>"); document.write("ParseInt Output: " + parseInt(num3),"<br/>"); document.write("typeof Output: " + typeof(num3),"<br/>");
- toFixed(N) function is used with float type variables and used to limit the decimal part to N digits.
- parseInt(float) function is used with float type variables and used to convert them into integers by removing the decimal part.
- typeof(type) function is used with any type of variable and used to print their data types.
document.write("Is 10 > 4 AND 6 < 9 : " + Boolean(10 > 4 && 6 < 9),"<br/>"); document.write("Is 10 == 4 OR 4 != 4 : " + Boolean(10 == 4 || 4 != 4),"<br/>");
- == checks the two values and returns true if they are the same.
- != checks the two values and returns true if they are not the same.
- a < b checks the two values and returns true if b is greater than a.
- a > b checks the two values and returns true if a is greater than b.
- && is used to check more than one conditions and returns true if all of them are correct.
- || is used to check more than one conditions and returns true if any of them is correct.