Samantha Ming LogoSamantha Ming

  • Home
  • About
  • Code Tidbits
  • Blog
  • Podcast
  • Recommendations
  • Contact

Trick to Adding String and Number

The unary + operator is a shortcut to convert a string into a number 🤩

Problem: Adding strings that contain numbers does NOT add them. Instead, the strings are concatenated ❌

Solution: Convert the string into a number. Then you can calculate the sum ✅

const string = "100";
const number = 5;

// This doesn't return the sum, it's concatentated
console.log(string + number) // 1005

// Prepend string with "+" to calculate the sum
console.log(+string + number) // 105

Resources

  • https://medium.com/@nikjohn/cast-to-number-in-javascript-using-the-unary-operator-f4ca67c792ce

Like ❤️

Like this on Twitter

Like this on Instagram

Trick to Adding String and Number

What I use

If you're interested in what I use to create this code tidbits, I list them here.

More Code Tidbits
  • Home
  • About
  • Code Tidbits
  • Blog
  • Podcast
  • Recommendations
  • Contact
  • What I use
  • Courses I Love
  • Podcasts I Love
  • Tech Stack
  • Speaking

© Copyright 2019. Samantha Ming