More Variable Reassignment

The following example shows how to increment the variable x by 2 (e.g. reassign the variable x to a value that is two greater than the current value that x is assigned to):

var x = 88; // x is assigned to the value 88
x = x + 2; // x is incremented by 2
console.log(x); // 90

The statement x = x + 2; executes the code to the right of = first, then reassigns x to the new value. x = x + 2; reassigns x to the value 90.

JavaScript provides a few shortcuts for common operations such as these. Here's the shortcut notation for adding 5 to the variable y:

var y = 3;
y += 5; // y is reassigned to 8

Notice that y += 5; is the same as y = y + 5;.

Another shortcut — the ++ operator — is used to increment a variable by 1, which proves very useful for loops (as we'll see in later sections). The shortcut x++ is equivalent to x = x + 1:

var i = 0; // i is assigned to 0
i++; // i is reassigned to 1
console.log(i); // prints 1 to the console
i++; // i is reassigned to 2
console.log(i); // prints 2 to the console

Shortcuts help experienced programmers write less code. New programmers sometimes find shortcuts confusing, but the shortcuts are well worth learning. You will see them frequently.

Question Click to View Answer

What does the following code print to the console?

var ww = 3;
ww = ww - 2;
console.log(ww);
1

The ww variable is initially assigned to 3. ww is then reassigned to 1 (the right side of the equation, ww - 2, is executed first, and then ww is reassigned). Then ww is printed to the console.

What does the following code print to the console?

var lala = 66;
lala -= 3;
console.log(lala);
63

lala is initially assigned to 66. lala is then reassigned to lala - 3, or 63. lala -= 3 is the same as lala - 3.

lala = lala - 3; // reassigns lala to lala minus 3
lala -= 3; // shorthand notation for lala = lala - 3

What does the following code print to the console?

var counter = 4;
counter++;
console.log(counter);
5

counter is initially assigned to 4 and then reassigned to counter + 1. counter++ is shorthand notation for counter = counter + 1. Shorthand notation is useful for experienced programmers to complete common tasks with less typing. Shorthand notation is difficult for new programmers because there are multiple ways of writing the same thing (and the shorthand notation is usually less clear).

Show how the following statment can be written differently with the two different shorthand notations.

var sleepy;
sleepy = sleepy + 1;
sleepy += 1;

OR

sleepy++;
<-- Previous (Variable Practice) Next (Importance of Precise Language) -->