JavaScript tutorial:
Declaring and naming variables

Variables allow you to refer to stored data by name, and manipulate the data.

How to declare a variable

Unlike other languages like C++, C# or Java, JavaScript does not require that you declare a variable before using it, for example:

myName = "Steve";

If you use a variable in this way inside of a function, it will be globally available to the rest of the script, for example:

function setMyName()
{
MyName = "Steve";
}

setMyName()
alert(MyName);

To run the code, paste it into JavaScript Editor, and click the Execute button.

To make a variable local to a function, use the keyword var in front of the variable. Modify the code above to add var in front of MyName:

function setMyName()
{
var MyName = "Steve";
}

setMyName()
alert(MyName);

Try to run the the code again by clicking the Execute button. What happens? JavaScript Editor highlights and reports a reference error:

Because the variable MyName is now local to the setMyName() function, you can only use it within the function. Using var also helps the interpreter free the memory of the variables that are no longer needed.

JavaScript version 1.5 allows var to be used outside of a function. You can run a syntax check, but trying to execute the code within JavaScript Editor will cause the error "Script too large" to appear.

Examples:

MyName = "Steve"; // The value is stored in a variable of string type
MyAge = 23; // The value is stored in a variable of numeric type
BornInAustralia = true; // boolean type

 

Rules for naming variables

JavaScript is case-sensitive language. MyName and myName are therefore two different variables. To name a variable:

The first character must be a letter, or an underscore (_), or a dollar sign ($).

The subsequent characters can be letters, numbers, underscores, or dollar signs.

The variable must not contain any embedded space characters.

The variable name can't be a reserved word.

Examples:

myName // Valid variable

_indexNumber // Valid variable

6item // Invalid: starts with a number

Trying to use a variable that has not been declared generates an error. When you declare a variable without assigning it a value, it is undefined. You can assign a special value null to a variable.

myNumber = null;

document.write(myNumber);

Automatic conversion

JavaScript allows you to easily convert one type to another, for example:

price = 20;
str ="This book costs " + price + " dollars."

document.write(str);

  In this example, the price variable is automatically converted (or coerced) to a string. To run the code, paste it into JavaScript Editor, and click the Execute button.

Convert a string to a number is less straight-forward. Consider the following example:

price = "20";
price = price + 10;

document.write(price);

  Run this piece of code in JavaScript Editor and observe the result. It is not 30 as you might expect, but 2010 (the number 10 was automatically converted to a string).

In cases like this, it helps to use the explicit conversion functions like parseInt() and parseFloat():

 

price = "20";
price = parseInt(price) + 10;

document.write(price);

Data types

Apart from strings and numbers, JavaScript also has objects, Booleans, and two special data types: null and undefined:

String

Strings can have both single or double quotation marks, for example:

str = "This is a string";

 

str = 'This is a string';

str = ' "Do not mess up with my strings," he excalimed.'

Number Data Type

JavaScript supports both integer and floating-point numbers. Integers can be positive, 0, or negative; a floating-point number can contain either a decimal point, an "e" (uppercase or lowercase), which is used to represent "ten to the power of" in scientific notation, or both. These numbers follow the IEEE 754 standard for numerical representation. Last, there are certain number values that are special:

NaN, or not a Number

Positive Infinity

Negative Infinity

Positive 0

Negative 0

Integers can be represented in base 10 (decimal), base 8 (octal), and base 16 (hexadecimal).

Octal integers are specified by a leading "0", and can contain digits 0 through 7. If a number has a leading "0" but contains the digits "8" and/or "9", it is a decimal number. A number that would otherwise be an octal number but contains the letter "e" (or "E") generates an error.

Hexadecimal ("hex") integers are specified by a leading "0x" (the "X" can be uppercase or lowercase) and can contain digits 0 through 9 and letters A through F (either uppercase or lowercase). The letter "e" is a permissible digit in hexadecimal notation and does not signify an exponential number. The letters A through F are used to represent, as single digits, the numbers that are 10 through 15 in base 10. That is, 0xF is equivalent to 15, and 0x10 is equivalent to 16.

Octal and hexadecimal numbers can be negative, but cannot be fractional. A number that begins with a single "0" and contains a decimal point is a decimal floating-point number; if a number that begins with "0x" or "00" contains a decimal point, anything to the right of the decimal point is ignored.

Examples:

// Four floating-point numbers, equivalent to each other.
.0001, 0.0001, 1e-4, 1.0e-4

// A floating-point number, equivalent to 345.
3.45e2

// An integer number.
42

// An octal integer, equivalent to 255.
0377

// As octal numbers cannot have decimal parts, this is equivalent to 0.
00.0001

// An integer, equivalent to 378.
0378

// A hexadecimal integer, equivalent to 255.
0Xff

// A hexadecimal integer, equivalent to 14287.
0x37CF

// A hexadecimal integer, equivalent to 999.
0x3e7

// As hexadecimal numbers cannot have decimal parts, this is equivalent to 3.
0x3.45e2

 
Booleans

The possible Boolean values are true and false. You cannot use a Boolean type instead of numbers 1 and 0.

Undefined Data Type

A value that is undefined is simply a value given to a variable after it has been created, but before a value has been assigned to it.

Null Data Type

A null value is one that has no value and means nothing.

Next