WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript Variables


JavaScript Variables

Variables can be thought of as named containers.

JavaScript variables are containers for storing data values.

In this example, x, y, and z, are variables:

Example

var x = 8;
var y = 7;
var z = x + y;
Try it Yourself »

From the example above, you can expect:

  • x stores the value 8
  • y stores the value 7
  • z stores the value 15

Much Like Algebra

In this example, item1, item2, and total, are variables:

Example

var item1 = 8;
var item2 = 7;
var total = itme1 + item2;
Try it Yourself »

In programming, just like in algebra, we use variables (like price1) to hold values.

In programming, just like in algebra, we use variables in expressions (total = price1 + price2).

From the example above, you can calculate the total to be 11.


JavaScript Identifiers

All JavaScript variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y), or more descriptive names (age, sum, totalVolume).

The general rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter
  • Names can also begin with $ and _ (but we will not use it in this tutorial)
  • Names are case sensitive (y and Y are different variables)
  • Reserved words (like JavaScript keywords) cannot be used as names

The Assignment Operator

In JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.

This is different from algebra. The following does not make sense in algebra:

x = x + 8

In JavaScript, however, it makes perfect sense: it assigns the value of x + 8 to x.


JavaScript Data Types

JavaScript variables can hold numbers like 100, and text values like "John Doe".

In programming, text values are called text strings.

JavaScript can handle many types of data, but for now, just think of numbers and strings.

Strings are written inside double or single quotes. Numbers are written without quotes.

If you put quotes around a number, it will be treated as a text string.

Example

var pi = 3.14;
var person = "Sophie";
var answer = 'Yes I am!';
Try it Yourself »