Declaring Variables

Variables in JavaScript are containers for storing data values. The following statement declares the variable hello:

var catsounds;

Once variables are declared, they can be assigned to a value:

var catSounds;
catSounds = "meow";

The catSounds variable is now assigned to the value "meow". We can confirm this with console.log():

console.log(catSounds); // prints "meow" to the console

Variables can be declared and assigned in a single line of code:

var bestNumber = 8;

The statement above is equivalent to these two statements:

var bestNumber;
bestNumber = 8;

Once a variable is declared, it does not need to be re-declared. That is, you do not need to repeat the var symbol when re-assigning a variable to a new value. The following code is bad:

var sad;
var sad = "this code sucks"; // sad was already declared!  This is bad!

This is much better:

var happy;
happy = ":-)";
Question Click to View Answer

Declare the variable iAmSilly.

var iAmSilly;

Declare the variable goodPlayer and assign it to the value "Steve Kerr".

var goodPlayer;
goodPlayer = "Steve Kerr";

The goodPlayer variable can also be declared and assigned on a single line:

var goodPlayer = "Steve Kerr";

Assign the variable x to the value 3 and assign the variable y to the value 5. Print the sum of x and y to the console.

var x = 3;
var y = 5;
console.log(x + y);
<-- Previous (Introduction to Booleans) Next (Variables and Values) -->