You get strings a type for the input. You clould convert the strings to number with an unary +
.
The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values true
,false
, and null
. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.
BTW, you need no paramter for calling the function add
, because you do not use the value.
"use strict";
function add() {
var first = prompt(),
second = prompt();
return +first + +second;
// ^ ^
}
var sum = add();
console.log(sum);
For a safe addition, you could use a default value for NaN
values.
"use strict";
function add() {
var first = prompt(),
second = prompt();
return (+first || 0) + (+second || 0);
}
var sum = add();
console.log(sum);