First of all, your ternary operator seems to be quite repetetive. There is a way to make it shorter:
totalPrice = salesPrice + ( salesPrice <= 25 ? minShipping : maxShipping );
Then, it is a good habit to declare your variables before you use them using var
keyword. In this particular case the advice is useless, since the script will be executed in the global scope, so all your variables will end up being global.
Your version of script concatenates the result since the return type of window.prompt
is String
. And when the one tries to add a String
to a Number
, the latter just gets converted into a String
and the concatenation occurs.
You can explicitly convert String
to Number
by using built-in parseInt
(or parseFloat
) functions or by adding a plus sign.
<script type="text/javascript">
/*<CDATA[[*/
var salesPrice, minShipping, maxShipping, totalPrice;
salesPrice = +window.prompt( 'Please Enter Purchase Price?', '' ),
minShipping = salesPrice * 1.5 / 100;
maxShipping = salesPrice * 10 / 100;
totalPrice = salesPrice + ( salesPrice <= 25 ? minShipping : maxShipping );
alert( totalPrice );
/*]]>*/
</script>
0
solved Instead of adding together, it concatenates [duplicate]