Variable reassignment

The following statement declares the variable b and assigns b to the value "hello world".

var b = "hello world";

Variables can be reassigned to other values. The following statement reassigns the variable b to the value 3.

b = 3;
console.log(b) // 3

When variables are reassigned, they lose memory of any former values. In the above example, when the variable b is reassigned to 3, b forgets that it was once assigned to "hello world". It is as if

Variables can be reassigned multiple times:

var funny = "homer";
funny = "otto";
console.log(funny); // "otto"
funny = "arrested development";
console.log(funny); // "arrested development"
funny = "cops";
console.log(funny); // "cops"

Notice that the var keyword is not used when the variable is reassigned. The var keyword is only needed when the variable is declared. After the variable is declared, var isn't needed anymore.

Question Click to View Answer

What does the following code print to the console?

var country = "Argentina";
country = "Bolivia";
country = "Colombia";
console.log(country);

"Colombia"

The country variable is initially assigned to "Argentina", then reassigned to "Bolivia", then reassigned to "Colombia".

What does the following code print to the console?

var person = "Frank";
person = 3;
console.log(person);

3

The person variable was initially assigned to the string "Frank" and then reassigned to the number 3.

What does the following code print to the console?

var blah = "meh";
var motivation = "super!!!";
blah = motivation;
console.log(blah);

"super!!!"

The blah variable is initially assigned to the "meh" string. The motivation variable is initially assigned to the "super!!!" string. blah is then reassigned to the same value that motivation is assigned to (e.g. blah is reassigned to "super!!!").

<-- Previous (Variables and Values) Next (Variable Practice) -->