JavaScript Tutorial - Expressions and Assignments

Left
Right

An expression is something that returns a value. The following operators are a few that can be used and are listed from highest to lowest precedence:
( ) parentheses
-- ++ decrement and increment
- negation
* / % multiplication, division, and modulo
- + subtraction and addition
= assignment
-= += *= /= etc. assignment with operation
, multiple evaluation
There are a lot more operators and for the current level it's not necessary to go into too much detail.

The concept of precedence is that some operators are more important than other operators, and need to be performed first.

For example: 2 + 3*4

Can be evaluated from left to right: (2+3)*4 = 20

However, the correct way is multiplication then addition: (2 + (3*4)) = 14

For strings the only meaningful operator is `+' for concatenation (or simply cat).

Example: work/expr.html

<HTML>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
// show precedence
document.writeln("<BR>(2+3)*4 = ",(2+3)*4);
document.writeln("<BR>(2+(3*4)) = ",(2+(3*4)));
document.writeln("<BR>2+3*4 = ",2+3*4);
// strings can only "cat"
document.writeln("<BR>'hello ' + 'world!' = ",'hello ' + 'world!');
// this is Not-A-Number
document.writeln("<BR>'hello ' - 'o' = ",'hello' - 'o');

// some assignments of variables to expressions
var i,j,k;
i = 1 + 2*3 + 4;
j = i + 4;
j = j + 1;	// not an equation ... an assignment
k = i = ++j;	// because `=' is an operator ... can chain several together
document.writeln("<BR>i = ",i);
document.writeln("<BR>j = ",j);
document.writeln("<BR>k = ",k);
</SCRIPT>
</BODY>
</HTML>

HOMEWORK:

  1. Write a JavaScript page that sets a number of variables to the following values 0, 32, 70, 100, 212
    and suppose one of the variable names is f then compute the expression 5/9*(f - 32) and output f and the value for that expression using document.writeln as in the above example.
    (This is the conversion expression from Fahrenheit to Celsius temperature.)
Left
Right
Slide 5