Variables¶
The declaration of a variable is possible by using one of the keywords:
const
let
var
The next step is to enter the variable name. To assign a value to a variable, we use the equal sign =
. In case of using const
, we need to make this assignment during the declaration. However, using the keywords let
orvar
, we can do it later.
The variables in JS are dynamically typed. This means that during the declaration we do not 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 the numeric type, but there is nothing to prevent you from assigning a new value of a different type to it, e.g.:
variableExample = 'And now I am a string woohoo! Can't do this in Java';
Now the variable variableExample
is of typestring
. In JavaScript, you can assign any type of value ** to a variable at any time.
const
¶
We use the const
keyword to denote variables that are constants. We cannot declare another constant with the same name, but the most important feature of such a "variable" is the fact that we cannot assign a different value to a constant once assigned. In turn, it is possible to change the content of the object to which such a reference points, for example:
const iAmConstantObject = {
foo: '1',
bar: '2'
}
iAmConstantObject.bar = '3';
//iAmConstantObject = 'cannot do it';
let
and var
¶
The keywords let
andvar
denote variables to which we can assign new values after declaring the variable. There are, however, important differences between var
andlet
:
- you cannot re-declare a variable
let
with the same name,var
allows it
var foo = 10;
let bar = 20;
var foo = 15;
let bar = 30; // here we will have an error: Uncaught SyntaxError: Identifier 'bar' has already been declared
Moreover:
let
offers [scope] (scope_variable_range.md) block, whilevar
scope is functionallet
is not hoisted.
NOTE: Given the choice of
var
andlet
, you'd better declare variables withlet
.
Variable naming¶
JS, like other languages, has certain variable naming conventions. They are similar to those in Java, i.e .:
- the variable name should start with a lowercase letter
- subsequent words are written together, starting each next we use a capital letter - this is the so-called camelCase notation
- variable name cannot start with a digit (0-9)
- variable name cannot contain spaces
- variable name cannot contain Polish letters
- variable name cannot be a keyword reserved by JavaScript.
Also keep in mind that in JS there is a distinction between uppercase and lowercase letters.
var foo;
var Foo; // these are two different variables