DEV Community

Cover image for JavaScript Struggles - Part 3 | String Auto Converting
Abdelrahman Dwedar
Abdelrahman Dwedar

Posted on

5 1

JavaScript Struggles - Part 3 | String Auto Converting

One of the weirdest things that JS do is converting string variable to numbers by itself.

When does it convert string to number?

We have 4 operators that can turn the string to number when the string value is numbers:


Plus (+)

In JavaScript the plus operator have 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
Enter fullscreen mode Exit fullscreen mode

2- When you use the + with a string that contains text, it'll not be converted to number; it'll be added to the text.

console.log("Hey"+"There"); // Outputs: HeyThere
Enter fullscreen mode Exit fullscreen mode

Minus (-)

Whenever we use - in our code the string automatically get converted to number.

E.g.

console.log('5' - 1); // Outputs: 4
console.log('5' - '2'); // Outputs: 3
Enter fullscreen mode Exit fullscreen mode

Multiply (*)

Whenever we use * in our code the string automatically get converted to number.

console.log('5' * 3); // Outputs: 15
console.log('5' * '2'); // Outputs: 10
Enter fullscreen mode Exit fullscreen mode

Divide (/)

Whenever we use / in our code the string automatically get converted to number.

console.log('6' / 2); // Outputs: 3
console.log('9' / '3'); // Outputs: 3
Enter fullscreen mode Exit fullscreen mode

Thanks for reading! 😁

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (4)

Collapse
 
tourmaline profile image
Tourmaline

Thanks for the post! There are also the circumstances when the -, * and / operators are used with strings that are not numbers like -'string'; or 'string' * '5'; and they just evaluate to NaN.

Collapse
 
abdelrahman_dwedar profile image
Abdelrahman Dwedar

Glad you liked it! 😊

I'm happy you noticed that, actually I said earlier that if you converted a string that contains text it'll be NaN in the pervious part .

Have a nice day

Collapse
 
tourmaline profile image
Tourmaline

Thanks for the quick answer, I will check the rest of the parts of this series since it has interesting information.

Thread Thread
 
abdelrahman_dwedar profile image
Abdelrahman Dwedar

Thanks for reading, I hope you liked them. 👍

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay