Variable Declaration is one of the main staples in JavaScript coding. Variables are used for multiple reasons. Let's get into one of the uses for variables.
Holding Data
Variables hold data for different reasons and use. At times a programmer needs to store the name or age of the user to track to create functions and more. variables also store data so that it can be manipulated by the user
var name = 'Chris';
name += ', joseph'
console.log(name)
//should return 'Chris, joseph'
Different types of Declarations
There are three different declarations we learned. They all have different scopes, work differently, and hoisting. These are let, const, and var. When it comes to how these work differently it is simple.
-Var
Var is globally scoped. This means whenever var is used to initialize a variable that variable is automatically pushed up to the global scope. Unless the var is initialized inside of the function scope then it will be function scoped.
for Ex:
//globally scoped
var scope = 'global'
function findScope(){
var scope2 = 'function
}
console.log(scope) //returns 'global'
console.log(scope2)//returns undefined
this is the only problem with the var initialization if you want to edit or change code inside of the function it can't be accessed in the global and the function scope and both be changed.
-Let
Let is defined in the block scope. This means that wherever it is called is where the scope is. So if I were to initialize let in a function I wouldn't be able to log it in the global context. Let can also be mutated but not re-initialized.
//let scoped
let scope = 'global';
function letFunc(){
let scope2 = 'func'
console.log(scope2)//returns func
}
console.log(scope)//returns global
console.log(scope2)//returns error
so depending on where let is logged and declared that is how we get around the scope and hoisting of let.
const
Just like let, const is block-scoped. This means that const can only be mutated in the cope of the initialization. Const is different though because when const is declared it can't be re-assigned or re-declared. the only issue is when used with an object. when using dot.notation const declaration objects key/value pairs can be manipulated.
const me = {
name: 'chris',
age: 22
}
//the only way to edit const me
me.name = 'chris!'
Top comments (0)