Variables¶
The declaration of a variable is possible by using one of the keywords:
const
let
var
The next step is to enter a variable name. To assign a value to a variable, use the equals sign =
. If we use const
, we must make this assignment during declaration. However, using the keyword let
or var
, we can do this later.
Variables have their type assigned dynamically. This means that during the declaration, we don't specify the variable type and we can assign an object of any type, e.g:
var variableExample = 10;
In the example above, the variable named variableExample
is of [numeric] type (data_types/number.md), but nothing stands in the way of assigning a new value of another type to it, e.g:
variableExample = 'And now I am a string woohoo! Can\'t do this in Java';
Now, the variable VariableExample
is already of type string
. In JavaScript you can assign a value of any type to a variable at any time.
const
¶
The keyword const
means a variable that is fixed. We cannot declare another constant with the same name, but the most important feature of such a "variable" is that once a constant is assigned, we cannot assign another value to it. In turn, it is possible to change the content of the object to which such a reference indicates, for example:
const iAmConstantObject = {
foo: '1',
bar: '2'
}
iAmConstantObject.bar = '3';
//iAmConstantObject = 'cannot do it';
let
and var
¶
Keywords let
and var
mean variables to which we can assign new values after declaring a variable. However, there are important differences between var
and let
:
- the variable
let
of the same name cannot be re-declared, thevar
allows this
var foo = 10;
let bar = 20;
var foo = 15;
let bar = 30; // we get an error: Uncaught SyntaxError: Identifier 'bar' has already been declared
Furthermore:
NOTE: When you have a choice of
var
andlet
, it is better to declare variables withlet
.
Naming conventions¶
JS, like other languages, has some variable naming conventions:
- the name of the variable should start with a lowercase letter
- consecutive words are written together. When starting every new one, we use a capital letter - it's called a camelCase notation
- variable name cannot start with a digit (0-9)
- the name of the variable cannot contain any spaces
- the name of the variable cannot contain characters specific to countries
- the variable name cannot be a keyword reserved by JavaScript.
Please also note that JS differentiates between upper and lower case letters.
var foo;
var Foo; // these are 2 different variables