- Three ways to declare variables in JavaScript:
- var
- let
- const
- For example:
var one = 1;
let two = 2;
const three = 3;
- Each Keyword has its own purpose!
- var
- Original way to declare variables in JavaScript
- A function scoped variable declaration, meaning that the variable, when defined, is available anywhere within that function.
- The variable is even available in the function before it was declared.
- The variable can be changed within the scope, meaning it is a immutable variable type. It can be reassigned, its data type can be changed
- let
- Similar to var
- A block scoped variable declaration, meaning that the variable is only available within a block that has been denoted with a set of open and closed curly brackets
- can be changed in scope
- only usable after the declaration of the variable
- const
- Block scoped, like let
- cannot be chaned
- when you have set a variable that you have defined as a const, meaning a constant value, you cannot change what that assignment is
- only available after declaration
- What to use when?
- const by default
- use as the “go-to” variable declaration
- makes life easier for yourself and others when looking at your code, as it cannot be changed throughout the program and it will only have one value.
- lower chance for bugs
- let in loops
- still very useful
- use inside of a block scope when it is desirable to create a new variable every time the loop happens.
- var
- partially obselete, as let and const basically cover all of its use cases, and let and const remove some of the issues with using a var type variable declaration
from Declaring variable: 9 of 51 (YouTube)