0

All except + do the math. How do I do an actual addition mathematically? Don't ask why I need it. I'm curious.

let first = "2" + 2  
let second = 4 + 4  
let third = first + second  
console.log(third)  

logged 228

let first = "2" + 2  
let second = 4 + 4  
let third = first - second  
console.log(third)  

logged 14

let first = "2" + 2  
let second = 4 + 4  
let third = first * second  
console.log(third)  

logged 176

let first = "2" + 2  
let second = 4 + 4  
let third = first / second  
console.log(third)  

logged 2.75

  • 1
    `-`, `*`, `/` are only mathematical operators but `+` can be both mathematical and **string concatenation** operator. When either of the attends is non-numeral(including numbers in string format), it will be a string concatination operation. To force `+` be mathematical, you need both attends to be numbers: (e.g. `Number(a) + Number(b)`) – Hao Wu Jan 24 '23 at 02:02
  • So, there is no way to read the number that's made in a string and use that as a mathematical variable for + operations? I didn't quite get the last part of your answer :/ – Quadron LT Jan 24 '23 at 02:23
  • There is, but the simplest way to do it is to make both of them `number` no matter what their original types are before the `+` taking effects (even when they are already numbers). There are numerous ways to do it, `Number(x)`, `+x` and `parseFloat(x)` etc. – Hao Wu Jan 24 '23 at 02:34

0 Answers0