Skip to Content
JavaScript: The Definitive Guide, Fourth Edition
book

JavaScript: The Definitive Guide, Fourth Edition

by David Flanagan
November 2001
Intermediate to advanced
936 pages
68h 43m
English
O'Reilly Media, Inc.
Content preview from JavaScript: The Definitive Guide, Fourth Edition

Assignment Operators

As we saw in the discussion of variables in Chapter 4, = is used in JavaScript to assign a value to a variable. For example:

i = 0

While you might not normally think of such a line of JavaScript as an expression that can be evaluated, it is in fact an expression and, technically speaking, = is an operator.

The = operator expects its lefthand operand to be either a variable, the element of an array, or a property of an object. It expects its righthand operand to be an arbitrary value of any type. The value of an assignment expression is the value of the righthand operand. As a side effect, the = operator assigns the value on the right to the variable, element, or property on the left, so that future uses of the variable, element, or property refer to the value.

Because = is defined as an operator, you can include it in more complex expressions. For example, you can assign and test a value in the same expression with code like this:

(a = b) == 0

If you do this, be sure you are clear on the difference between the = and == operators!

The assignment operator has right-to-left associativity, which means that when multiple assignment operators appear in an expression, they are evaluated from right to left. Thus, you can write code like this to assign a single value to multiple variables:

i = j = k = 0;

Remember that each assignment expression has a value that is the value of the righthand side. So in the above code, the value of the first assignment (the rightmost ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

John Pollock
JavaScript Cookbook, 3rd Edition

JavaScript Cookbook, 3rd Edition

Adam D. Scott, Matthew MacDonald, Shelley Powers

Publisher Resources

ISBN: 0596000480Supplemental ContentCatalog PageErrata