var x = 10 + Number("1"+"6"); console.log(x);
returns: 26
var y = 10 + 1 + 6; console.log(y);
returns: 17
var x = 10 + Number("1"+"6"); console.log(x);
returns: 26
var y = 10 + 1 + 6; console.log(y);
returns: 17
You're adding two strings together inside Number(...)
:
"1" + "6" = "16"
So the line basically comes down to:
var x = 10 + Number( "16" )
> 26
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.
"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;
}