11.12.2012 Views

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Operators<br />

<strong>JavaScript</strong> supports a variety of operators. Some of them, like those for arithmetic and<br />

comparison, are easy for even those new to programming to understand. Others, like the<br />

bitwise AND (&), increment (++), and some conditional (?:) operators, may be less obvious to<br />

those who have not programmed before. Fortunately for readers of all levels, <strong>JavaScript</strong><br />

supports few operators that are unique to the language, and the language mimics C, C++, and<br />

Java closely in both the kinds of operators it provides and their functionality.<br />

Assignment Operator<br />

Probably the most basic operator is the assignment operator (=), which is used to assign a<br />

value to a variable. Often this operator is used to set a variable to a literal value, for example:<br />

var bigPlanetName = "Jupiter";<br />

var distanceFromSun = 483600000;<br />

var visited = true;<br />

Generally, the assignment operator is used to assign a value to a single variable, but it is<br />

possible to perform multiple assignments at once by stringing them together with the =<br />

operator. For example, the statement<br />

var x = y = z = 7;<br />

sets all three variables to a value of 7.<br />

Assignments can also be used to set a variable to hold the value of an expression. For<br />

example, this script fragment demonstrates how variables can be set to the sum of two literal<br />

values as well as a combination of literals and variables:<br />

var x = 12 + 5; // x set to 17<br />

var a, b = 3; // a declared but not defined, b set to 3<br />

a = b + 2; // a now contains 5<br />

Arithmetic Operators<br />

<strong>JavaScript</strong> supports all the basic arithmetic operators that readers should be familiar with,<br />

including addition (+), subtraction (–), multiplication (*), division (/), and modulus (%, also known<br />

as the remainder operator). Table 4-1 details all these operators and presents examples of<br />

each.<br />

Table 4-1: Basic Arithmetic Operators<br />

Operator Meaning Example Result<br />

+ Addition var x = 5, y = 7;<br />

var sum;<br />

sum = x+y;<br />

– Subtraction var x = 5, y = 7;<br />

var diff1, diff2;<br />

diff1 = x–y;<br />

diff2 = y–x;<br />

Variable sum<br />

contains 12.<br />

Variable diff1<br />

contains –2 while<br />

variable diff2<br />

contains 2.<br />

* Multiplication var x = 8, y = 4; Variable product

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!