JavaScript Struggles — Part 3 | String Auto Converting
One of the weirdest things that JvaScript do is convert string variable to numbers by itself.
When does it convert a string to a number?
We have 4 operators that can turn the string into a number when the string value is numbers:
- Plus (+)
- Minus (-)
- Multiply (*)
- Divide (/)
Plus (+)
In JavaScript, the plus operator has two cases.
1- When you use the + with a string
that only have numbers it'll be converted automatically to number
.
console.log('1'+'2'); // Outputs: 3
2- When you use the + with a string
that contains text, it'll not be converted to numbers; it'll be added to the text.
console.log("Hey"+"There"); // Outputs: HeyThere
Minus (-)
Whenever we use — in our code the string automatically gets converted to a number.
E.g.
console.log('5' - 1); // Outputs: 4
console.log('5' - '2'); // Outputs: 3
Multiply (*)
Whenever we use * in our code the string automatically gets converted to a number.
console.log('5' * 3); // Outputs: 15
console.log('5' * '2'); // Outputs: 10
Divide (/)
Whenever we use / in our code the string automatically gets converted to a number.
console.log('6' / 2); // Outputs: 3
console.log('9' / '3'); // Outputs: 3
Thanks for reading! 😁