Type conversion is when we manually convert from one type to another type in JS.
const randomYear = "2001"; console.log(Number(randomYear) + 50);
In this code, I have stored a string value in the randomYear variable. Then, in the second line, I converted randomYear value to a number using the Number() method. This is type conversion where I have converted a string to a number data type.
If I didn’t convert this value to a number then in that case, it will behave as a string. So, it is like “2001” + 50 and this plus symbol concatenates these two values. So, the output will be 200150.
In this code, you can see, I am trying to convert a string to a number. But in this case, it will give us the output NaN because the Number() method can only convert string values that are numbers but are written in ” “.
let a = String(2); console.log(typeof a);
We can convert a number to a string type using the String() method, as I did in the above code.
Basically, In type conversion, we are changing the data type of the value. Such as converting a string to a number, a number to a string, etc.
Let’s understand using some examples.
let a = "50"; let b = "2"; let c = a / b; console.log(c); console.log(typeof c);
Output: 25 number
In this code, I have declared a and b with a string value value and divided a by b. The output value is of number type.
let num = "25" + 1; num = num * 2; console.log(num); console.log(typeof num);
Output: 502 number
- In line number 1, “25”+1 will be 251 because 25 is a string and 1 is a number. So, in this case both values will concatenate.
- In line number 2, “251” * 2 will be 502.
- In the console, output is 502.
- This value is of number type, you can check it in the console also using typeof.
let num = "25" + 1; num = num - 11; console.log(num); console.log(typeof num);
Output: 240 number
let value = "I did total" + " " + 2 + " " + "goals"; console.log(value); console.log(typeof value);
Output: I did total 2 goals string
In line number 1, I have written both string and number data type and stored it in value variable. But the output I get is of String type. I have used the typeof in line 3 to check the data type.
When we use + to concatenate two or more things then it will always give us a string data type.
console.log("12" + "17" + "200");
In this code, the values are in string type. So, in this case + will concatenate these values.
Point to Note:
- If we are writing a number in ” “ and then try to add two or more numbers. Then it will behave as a string and it will give us a concatenated string. As you can see in the example 5 above.
- If we are writing a number in ” “ and then try to divide, multiply, or subtract two or more numbers. Then in this case, the string will behave as a number type and the output value is also a number data type. As you can see in the example 1, 2, and 3 above.