errantwriter

12-25-2010, 01:42 AM

Hi,

I'm just learning JS by going through a book, while trying one of the examples in the book I ran into a problem with " + " operator. It think it's best I show by example (don't worry it's a fairly short script):

Script

/* This is an attempt to do some math with javascript */

var a;

var b;

var c;

a = prompt("Pick your favorite number");

b = prompt("Pick your second favorite number");

c = a + b

document.write("a = " + a + ", b = " + b + ", c = " + c + "<br />");

document.write("<br />a + b = " + c + "<br />");

c += 6

document.write("<br />c + 6 = " + c + "<br />");

c -= 5

document.write("<br />c - 5 = " + c + "<br />");

c *= 3

document.write("<br />c * 3 =" + c + "<br />");

c /= 2

document.write("<br />c / 2 = " + c + "<br />");

c %= 7

document.write("<br />c % 7 = " + c + "<br />");

if (c > 0) {

document.write("<br /> Wrong!");

}

else {

document.write("<br /> You, I like")

}

Output

a = 3, b = 4, c = 34

a + b = 34

c + 6 = 346

c - 5 = 341

c * 3 =1023

c / 2 = 511.5

c % 7 = 0.5

Wrong!

As you can see the script doesn't execute the mathematical operation for addition. It instead strings it together. What am I doing wrong?

I'm just learning JS by going through a book, while trying one of the examples in the book I ran into a problem with " + " operator. It think it's best I show by example (don't worry it's a fairly short script):

Script

/* This is an attempt to do some math with javascript */

var a;

var b;

var c;

a = prompt("Pick your favorite number");

b = prompt("Pick your second favorite number");

c = a + b

document.write("a = " + a + ", b = " + b + ", c = " + c + "<br />");

document.write("<br />a + b = " + c + "<br />");

c += 6

document.write("<br />c + 6 = " + c + "<br />");

c -= 5

document.write("<br />c - 5 = " + c + "<br />");

c *= 3

document.write("<br />c * 3 =" + c + "<br />");

c /= 2

document.write("<br />c / 2 = " + c + "<br />");

c %= 7

document.write("<br />c % 7 = " + c + "<br />");

if (c > 0) {

document.write("<br /> Wrong!");

}

else {

document.write("<br /> You, I like")

}

Output

a = 3, b = 4, c = 34

a + b = 34

c + 6 = 346

c - 5 = 341

c * 3 =1023

c / 2 = 511.5

c % 7 = 0.5

Wrong!

As you can see the script doesn't execute the mathematical operation for addition. It instead strings it together. What am I doing wrong?