javascript interactive

JavaScript Interactive — a console crash course


2.1 Variables & Assignment

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.
>>>
var a, b
undefined
Variable names are defined using the var keyword. Several variables can be named in a single statement.
>>>
var a = 2
undefined
Optionally, an initial value can be provided. It is not an error to reuse an existing variable name. It will create a new variable that shadows (hides) the previous one.
>>>
b
undefined
If no value was specified when declaring the variable, undefined is used as the default.
>>>
b = 3
3
The assignment operator = is used to change the value of a variable.
>>>
c = 5
5
Beware! If a variable name hadn't been previously defined with var, a new global variable is created by the assignment. It is a common cause for bugs.
>>>
c += 1
6
The modifying assignment operators (+=, -=, *=, /=, %= and a few others we'll see later) allow for easy updates.
>>>
++c
7
The ++ and -- operators increment or decrement a numeric variable and return its value. If placed after the variable name, the current value is returned (but the variable is still modified).
>>>

Index 1 2 3 4 5 6 7 8