0

var x = 10 + Number("1"+"6"); console.log(x);

returns: 26


var y = 10 + 1 + 6; console.log(y);

returns: 17

  • 2
    Duplicate of [JavaScript adding a string to a number](https://stackoverflow.com/questions/16522648/javascript-adding-a-string-to-a-number) – MrUpsidown Feb 14 '20 at 12:18

3 Answers3

4

You're adding two strings together inside Number(...):

"1" + "6" = "16"

So the line basically comes down to:

var x = 10 + Number( "16" )
> 26
Yannick K
  • 4,887
  • 3
  • 11
  • 21
-1

In your first example Number("1"+"6"), "1" and "6" evaluate as strings (because of the quotes). When JS adds strings it concatenates them, so "1" + "6" becomes "16" the same way that "Hello " + "world" becomes "Hello world".

In your second example all of the numbers are treated as numbers, so they are added as you expect.

ecg8
  • 1,362
  • 1
  • 12
  • 16
-1

"1"+"6" = "16" : concatenation fo 2 strings Number("1"+"6") = Number("16") = 16

10 + 16 = 26

    let x = 10 + Number("1") + Number("6"); //for x to equal 17

here a function i use to sum numbers regardless of arguments are numbers or strings (return null if any of the arguments is not a number)

function sumNumbers(){
    let result = 0;
    for(arg of arguments){
        let nArg = Number(arg);
        if(isNaN(nArg)){
            return null;
        };
        result+=nArg; 
    }
    return result;
}
amirX
  • 1