# Simple Statements

### Simple Statements

Some JavaScript statements extend beyond a line, such as those for loops, which have a beginning and end. Others, though, stand all on their own: one statement, one line. Among these simple statements are those for assignment.

#### The Assignment Statement

The most common statement is the assignment statement. It's an expression consisting of a variable on the left side, an assignment operator (=), and whatever is being assigned on the right.

The expression on the right can be a literal value:

nValue = 35.00;

Or, a combination of variables and literals combined with any number of operators:

nValue = nValue + 35.00;

And it can be a function call:

nValue = someFunction(  );

More than one assignment can be included on a line. For instance, the following assigns the value of an empty string to multiple variables, on one line:

var firstName = lastName = middleName = "";

Following the assignment statement, the second most common type of statement is the arithmetic expression that involves the arithmetic operators, discussed next.

#### Arithmetic Statements

In the last section, the second example was a demonstration of a binary arithmetic expression: two operands are separated by an arithmetic operator, leading to a new result. When paired with an assignment, the result is then assigned to the variable on the left:

nValue = vValue + 35.00;

More complex examples can use any number of arithmetic operators, with any combination of literal values and variables:

nValue = nValue + 30.00 /  2 - nValue2 * 3;

The operators used in the expression come from this set of binary operators:

+

-

For subtraction

*

For multiplication

/

For division

%

To return the remainder after division

These are considered binary operators because they require two operands, one on either side of the operator. Any number can be combined into one statement and assigned to one variable:

var bigCalc = varA * 6.0 + 3.45 - varB / .05;

This code shows the binary operators working with numbers. How about if the values are strings?

In some of the previous examples, I concatenated (joined) strings together using the addition sign (+), just as if I were adding two numbers together:

var newString = "This is an old " + oldString;

When the plus sign (+) is used with numbers, it's the addition operator. However, when used with strings, it's the concatenation operator. With other binary operators, you can use a string as an operand, but the string has to contain a number. In cases such as this, the value is converted to a number before the expression is evaluated:

var newValue = 3.5 * 2.0; // result is 7
var newValue = 3.5 * "2.0"; // result is still 7
var newValue = "3.5" * "2.0"; // still 7

On the other hand (and it's important to be aware of the distinction), if you add a number literal or variable and a string, the number is the value that's converted from number to string.

In the following example, you might expect to get a value of 5.5 but instead get a new string, "3.52.0":

var newValue = 3.5 + "2.0"; // result is a string, "3.52.0"

This one can trip you up quite frequently. Be very, very careful when mixing types with implicit conversion; a simple accident in any of the values could lead to surprising results. When you think the data type of one variable is treated as a string by the JavaScript engine, a better approach is to use parseInt, parseFloat, or Number to explicitly convert the value:

var aVar = parseFloat(bVar) + 2.0;

#### The Unary Operators

In addition to the binary arithmetical operators just covered, there are also three unary operators. These differ from the earlier batch in that they apply to only one operand:

++

Increments a value

--

Decrements a value

-

Represents a negative value

Here's an example of a unary operator:

someValue = 34;
var iValue = -someValue;
iValue++;
document.writeln(iValue);

In the second line, the number is converted to a negative value through the use of the negative unary operator. The value is incremented by one using ++, which is a shorthand version of:

iValue=iValue + 1;

The end result is 33.

The increment and decrement operators have another interesting aspect to them. In an expression, if the operator is listed first, the value is adjusted before the result is assigned. However, if the operator is listed after the variable, the initial value in the variable is assigned, and the value is adjusted:

var iValue = 3.0;
var iValue2 = ++iValue; //iValue2 is set to 4.0, iValue has a value now of 4.0
var iValue3 = iValue++; //iValue3 is set to 4.0; iValue now has a value of 5.0
var iValue4 = iValue;   //both iValue4 and iValue have a value of 5.0

#### Precedence of Operators

There is a level of precedence to operators in JavaScript. In statements, expressions are evaluated left to right when all operators have the same precedence. If more than one type operator with more than one precedence is used in a statement, the rule is that the operator with higher precedence is evaluated first, then the rest of the expression is evaluated left to right.

Let's consider the following code:

newValue = nValue + 30.00 /  2 - nValue2 * 3;

If the value of nValue is 3 and the value of nValue2 is 6, the result is 0.

In detail, the division of 30.00 by 2 is evaluated first because it has higher precedence than the addition, resulting in a value of 15. The multiplication operator has the same precedence as that of division, but it occurs after the division. Because expressions are evaluated left to right when precedence is the same, the division is done first, then the multiplication. In the latter, the value in variable nValue2 is multiplied by 3, resulting in a value of 18. From that point on, the expression consists solely of addition and subtraction (equal precedence), and is evaluated left to right as:

newValue = nValue + 15  18;

The assignment operator has the lowest precedence, and once the arithmetic expression is evaluated completely, the result is assigned to newValue.

To control the impact of precedence, use parentheses around expressions you want evaluated first. Returning to the example, the use of parentheses can lead to widely different results:

newValue = ((nValue + 30.00) / (2 - nValue2)) * 3;

Now, addition and subtraction are evaluated first, before division and multiplication. The result of this expression is 24.75.

You all knew this from your basic math classes. However, it doesn't hurt to get a little reaffirmation: although it's in JavaScript, the rules are the same.

 Note that in JavaScript, unlike in other languages, the division results in a floating-point result, not a truncated whole number. The following results in a value of 1.5 rather than a rounded value of 1: iValue = 3 / 2;

In the examples so far, we're typed out the full expression when using binary operators. There is a shortcut method to these expressions, which we'll look at next.

#### Handy Shortcut: Assignment with Operation

Assignment and an arithmetic operation can be combined into one simple statement if the same variable appears on both sides of the operator, such as in the following:

nValue = nValue + 30;

The simplified statement is:

nValue += 3.0;

All of the binary arithmetic operators can be used in this type of shorthand technique, known as an assignment with operation:

nValue %= 3;
nValue -= 3;
nValue *= 4;
nvalue += 5;

This type of operation can also be used in combination with the four bitwise operators.

#### Bitwise Operators

 This section covers JavaScript bitwise operators, and assumes you have some experience with Boolean algebra. It's not a functionality that's used extensively in JavaScript and can be safely skipped during this first introduction to the language. If you're not familiar with Boolean algebra and want to continue with this section, there is excellent Boolean algebra reference, put together by the BBC (British Broadcasting Corporation), at http://www.bbc.co.uk/dna/h2g2/A412642.

Bitwise operators treat the operands as 32-bit values made up of a sequence of zeros and ones. The operators then perform, literally, a bitwise manipulation of the result; the type of manipulation depends on the type of operator:

&

Bitwise AND operation, in which the resulting bit is 1 if, and only if, both values are 1.

|

Bitwise OR operation on bits, in which the result is 1 only if one of the operand bits is 1.

^

Bitwise XOR operation on bits, in which the the combination of the two operand bits equals 1 if, and only if, both values are different. If the value of both is 1 or 0, the result is 0; otherwise, the result is 1.

~

Bitwise NOT operation on a bit, which returns the inverted value (complement) of the bit (i.e., 1 results in 0; 0 results in 1).

It might seem as if the bitwise operators don't have much use in JavaScript, except that they're a handy way of creating binary flags within a program. Binary flags are similar to variables except that they use much less memory (by a factor of 32). The Mozilla Core JavaScript 1.5 reference provides an example that uses binary flags: http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Operators:Bitwise_Operators. In the example, four flags are represented by the following variable:

var flags = 0x5;

This is equivalent to the binary value of 0101 (disregarding leading zeros):

flag A: false
flag B: true
flag C: false
flag D: true

Each bitmask flag is then represented as:

var flag_A = 0x1;
var flag_B = 0x2;
var flag_C = 0x3;
var flag_D = 0x4;

To test if flag_C is set in our flags variable, use the bitwise AND operator:

if (flags & flag_C) {
do stuff
}

In Figure, a binary flag and bitmasks are used to emulate the result of an imaginary form submission. In the example, we'll assume five fields are submitted, but only three have values: fields A, C, and E. If both A and C are filled in, a message to this effect is output in a dialog window.

##### Use of binary flags and bitmask to create memory-friendly flags

 Using Binary Flags

Imagine a form with five fields and a button here...

This is a way of conserving space in your application, as you can work with binary values within the space required for Boolean variables. However, this does compromise the code's readability.

 Another operator, the logical AND (designated by &&) is also introduced in Figure. This is covered in detail later in the section "The Logical Operators."

There is more in the Mozilla reference regarding the use of bitwise operators as a test of input; it's an interesting technique and an affirmation that though memory management is handled behind the scenes with JavaScript, there are tricks and techniques you can use to get an edge when you need one.

 There are three other bitwise operators: shift left (<<), shift right with sign (>>), and shift right with zero fill (>>>). These move the bits of the operand to the right or left by the number of places designated by the second operand (a value between 0 and 31): newValue = oldValue >>> 3;

This last example also introduces the concept of a different type of statement and set of operators: conditional statements, and relational and equality operators. We'll look at both in the next few sections.