1. Home
  2. Computing & Technology
  3. JavaScript

JavaScript Variables and Operators
9. Assignment Operators

By Stephen Chapman, About.com

We have already seen a few simple examples of assignment operators when we looked at assigning values to variables when we first define them. The same assignment operator works for assigning a replacement value to a variable. Here are some examples.


1 var price = cost + profit;
2 remains = purchased - eaten;
3 min = count++;

In 1 a new variable price is created. The values in cost and profit are added together and the result of this addition is stored in price. The values in cost and profit are not changed.

2 subtracts eaten from purchased and stores the result in remains.

3 copies the value from count into min. It then adds one to count so that count will be one greater than min after this statement runs.

Where we want to add one number to another and store the result in one of the existing fields rather than a new field JavaScript provides a shorthand notation. The same shorthand notation also exists for each of the other numerical operators.



fruit += apples;
price -= tax;
timeWorked *= days;
pages /= books;
entry %= selection;

The first of these statements has the same result as if we had put fruit = fruit + apples; The difference is that instead of adding fruit and apples together in a temporary field and then moving the result back into fruit the value of apples can be added to fruit directly.

Similarly price -= tax; is equivalent but more efficient than price = price - tax;, timeWorked *= days; is equivalent to timeWorked = timeWorked * days; and so on.

This tutorial first appeared on www.felgall.com and is reproduced here with the permission of the author.

Explore JavaScript
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. JavaScript
  4. Javascript Tutorials
  5. Learn Modern JavaScript
  6. 1. Variables and Operators
  7. JavaScript Variables and Operators - Assignment Operators>

©2009 About.com, a part of The New York Times Company.

All rights reserved.