Assignment:
The equal sign (=) is the assignment operator.operator Symbol Add and assign += subtract and assign -= multiply and assign *= divide and assign /= modulus and assign %=
Addition:
Assign returnValue the sum of x plus y. var x,y,returnValue; x = 30; y = 40; returnValue = x + y; //returnValue = 70 x = x + y; //x now contains the value 70, y remains at 40 y = y + 100; //y is now 140 Using the assignment operator x += y; //x now contains the value 70, y remains at 40 y += 100; //y is now 140 What happens when you assign a variable a string and add them together? The values are concatenated. a = "2"; b = "3"; returnValue = a + b; //returnValue = 23
Converting Data:
For data that you aren't sure is numeric or a string you can convert the string to a number using parseInt() or parseFloat() be carful when using the eval() function click here to see the demoWhat happens when the variable you are using does not contain a number? The previous example
was changed so x would contain the string "stuff". When using the eval() function, an error
is displayed and all processing stops.
When using parseInt() or parseFloat() no error is produced, however you will get an answer of
NaN - Not a Number.
The first part of the demo is commented out because the eval() function keeps the code from processing. To see the demo in action view the source and delete the comments.
click here to see the demotypeof() function
There is also a function to evaluate what is in a varaible. The function is typeof(). This function will be discussed more in chapter 7.Subtraction:
x = 30; y = 40; returnValue = y - x //returnValue = 10 x = x-y //x is now -10, y remains 40 x -= y //x is now -10, y remains 40 a="2"; b="4"; returnValue = a - b //returnValue -2 click here to see the demo
Increment, Decrement, and Assignment:
prefix and postfix operator click here to see the demo
Multiplication:
x = 30; y=40; returnValue = x * y; //returnValue = 1200 y = x * y //y is now 1200; y *= x //y is now 1200; click here to see the demo
Division:
x = 12; y=4; returnValue = x / y; //returnValue = 3 y = x / y //y is now 3; y /= x //y is now 3; click here to see the demo
Modulus:
When you divide 40/30 you get the value But what if you wanted the remainder? 40/30 is 1 with the remainder of 10. This is where the Modulus operator comes in handy x = 40; y=30; returnValue = x % y; //returnValue = 10 y = x % y //y is now 10; y %= x //y is now 10; click here to see the demo
click here to see the convert temperature program demo.