...

Strings to Numbers: Avoiding a Common Pitfall

let num1 = "5";

Is num1 a number? Or is it a string?

Numbers can sometimes be stored as strings, and this happens more often than you would think. This can lead to unexpected results when performing numeric operations, such as the + operation.

For example, if you try to add two numbers stored as strings, the + operator will concatenate them instead of performing addition:

let num1 = "5";
let num2 = "10";
let result = num1 + num2;
console.log(result); // Outputs "510"

To ensure proper addition, you can use the Number function to convert strings to numbers:

let convertedNum1 = Number(num1);
let convertedNum2 = Number(num2);
let sum = convertedNum1 + convertedNum2;
console.log(sum); // Outputs 15

Run the code sample to see both concatenation and proper addition in action.

Loading...

Output (Console)