So variables are like containers or boxes where you can store data.
Now, if you come from a C, C++ or Java background, then you may be using "int", "double", "string" keywords to declare a variable. In these languages, the value stored in a variable depends on the type of the variable you declared.
- We can declare the same variable multiple times using "var" in the current scope. It doesn't give any error.
- "var" uses the functional scope. So we can access a variable anywhere inside the function where it is declared. So if you declare and initialize a variable inside a block using the same name, that will modify the variable outside of the block scope.
- We can't declare the same variable multiple times using let in the current scope.
- "let" uses a blocked scope. It means we can define the same-named variables inside the different block scopes. Also, we can't access a variable outside of its block scope.
Now the main question is when to use which keyword. So, if you want a variable whose value may be changed later in the program, then use "var" or "let". If you declare a variable globally inside a function, use "var" and if you want to use it inside a blocked scope like if, loops etc., use "let". And if you declare a variable whose value never changed in the program, use "const". Ex: const PI = 3.14 etc.