When we give our variable a value, we’re doing two things. First we’re declaring the variable and second we’re defining the variable by giving it a value.
Let’s see a simple example of how to use a variable:
Usually, you wouldn’t take these two steps. You’d simply type:
We just initialized a variable called greeting, that holds the value of “Ruslan”!
We shouldn't just give random names to variables.
Another convention is that we should not start a variable name with an uppercase letter.
On the same note variables that are all in uppercase are reserved for constant that we know will never change. For example, the number PI.
To make sure that our variable names are descriptive. When you name your variables it should be really easy to understand exactly what value the variable is holding just by reading the name of the variable.
A variable name can only contain letters (a-z), numbers (0-9), underscores (_) and the dollar sign ($). An identifier cannot start with a digit.
Another variable name that's kind of reserved but still actually allowed to use is the word name. In some cases this creates some problems.
So let's learn how they are different and which one to use in which situations.
We use let keyword to declare variables that can change later. So basically during the execution of out program
So we use let to declare color and then we changed that later from "red" to "blue". And so, it's perfectly okay to declare a variable with let at one point in the program and then later assign a new value to it. In technical terms, we call this reassigning a value to a variable, or also we say that we mutate the color variable in this case.
So, when we need to mutate a variable that's the perfect use case for using let. And that also counts for the case that we want to declare empty variables. So for example, as we did here,
where we declared an empty firstName and then later reassigned that variable to "Ruslan".
On the other hand, we use the const keyword to declare variables that are not supposed to change at any point in the future. So the value in a const variable cannot be changed
So const keyword creates a variable that we cannot reassign or in technical terms, an immutable variable. So, a variable that cannot be mutated.
Now the fact that variables created with const are immutable also means that we cannot declare empty const variables.
For example, this is not legal:
And we will gen an error "Missing initializer in const declaration". This error message means that when using const, we need an initial value.
Best practice for writing clean code is to use const by default and let only when you are really sure that the variable needs to change at some point in the future.
Although it looks like var and let are very similar, below the surface they're actually pretty different. And actually there are also many differences between let, const and var. So, between all three of them. We will learn differences between them later.