Converting string to number when doing addition operation

Why would i have to covert string to number when doing addition, but don’t need to do so with other operators?

I know i am going to get it concatenated without converting it first. But why doesn’t it apply to other operators as well?

See what i did:

let ahg = "56";
let hyu = 2;
Number(ahg) / hyu;
ahg + hyu;
ahg ** 3;
let hyuu = "2";
hyuu ** 2;
typeof hyuu;
hyuu + 3

I’m no expert, but I would guess that since the other operators can’t be used on strings, JavaScript tries to guess and see if it can do the operation on the var as a number…

1 Like

Hello there,

I suppose whoever was involved in deciding the syntax thought it would be a useful shortcut as opposed to always using something more verbose like concat. In case you are unaware, this is another useful syntax that would achieve what you want:

let a = '12';
let b = 8;
let c = +a + b; // c === 20 (you could be more verbose with: +a + +b

Hope this helps

1 Like