Variables are declared with the var
keyword. JavaScript is
dynamically typed so every variable can hold a value of any data type.
Variables can be declared without an initial value.
Some example declarations:
var foo;
var bar = 42;
var foo, bar, baz;
var foo = 42,
bar = 'baz',
z;
Variables that don't explicitly get assigned an initial value have the value
undefined
.
ES2015
Since ES2015, let
and const
can be used in addition to var
. We will learn
how they differ from var
later. For now, lets have a look how const
differs
from var
or let
: const
can be assigned a value only once (constant).
Reassigning a value will either throw an error (in strict mode, see below) or
is silently ignored:
const foo = 42;
foo = 21; // error or ignored
const
s must be initialized with a value:
const foo; // error
foo = 42;
Variable names
Valid characters for variable names include a wide range of unicode
characters.
However, the name must start with a letter, _
or $
. Not doing so will
result in a syntax error.
Examples:
var π = 3.141;
var _foo = π;
var 0_bar = '...'; // Syntax error
Variable access
Trying to read an undeclared variable results in a runtime error:
var foo;
console.log(bar); // ReferenceError: bar is not defined.
However, writing to an undeclared variable is valid by default. It will create an implicit global variable and should thus be avoided:
function foo() {
bar = 42;
}
foo();
console.log(bar); // no error
If code runs in strict mode, assigning to an undeclared variable throws an error.
Strict mode
Strict mode is a mode of evaluating JavaScript that enforces stricter rules. It was introduced to "deprecate" certain patterns/behaviors that are considered bad or confusing.
Strict mode can be enabled for a JavaScript or a function by putting
'use strict';
at the beginning of it.
JavaScript has 6 data types. Five of those are so called primitive data types:
- Boolean
- Number
- String
- Null
- Undefined
Everything else that is not a value of one of the above types is an
- Object
As we will see in the following slides, objects belong to different kinds of "classes" of objects.
ES2015
ES2015 introduces a 6th primitive data type: [Symbol][]. Symbols are unique and immutable values.