-2
var apples = prompt('Please enter no. of apples');
var oranges = prompt('Please enter no. of oranges');
var fruits = apples + oranges;


document.write(fruits);

Why does it work with - and * and not +?

Thanks!

tadman
  • 208,517
  • 23
  • 234
  • 262
zenarthra
  • 17
  • 4
  • See also http://stackoverflow.com/q/17498883 http://stackoverflow.com/q/10414675 http://stackoverflow.com/q/22704963 http://stackoverflow.com/q/12044595 http://stackoverflow.com/q/21215122 and many, many other similar questions – p.s.w.g Aug 12 '14 at 01:20

3 Answers3

2

You're adding two strings together to get another string. That's how JavaScript does it.

Maybe what you want is numbers:

var fruits = parseInt(apples, 10) + parseInt(oranges, 10);

As a note, using prompt to collect information is utterly barbaric. What you need to do is have two input boxes and a submit trigger that does the math, or since it's so trivial, hook it up to trigger on any change to either value. jQuery basics here.

tadman
  • 208,517
  • 23
  • 234
  • 262
1

You're doing string concatenation with the + instead of an addition. Parse to float or int.

var fruits = parseFloat(apples) + parseFloat(oranages);

EasyCo
  • 2,036
  • 20
  • 39
0

prompt returns a string, thus it's appending the strings together. Javascript will convert to an int when you try other operators on the variables.

Use parseInt to make sure they're ints.

ChrisGheen
  • 984
  • 6
  • 17