I originally wrote a tutorial about Var, Let, and Const using Observable Notebook.
In the notebook, you can edit the code, so that you understand by doing.
As a junior dev, it seems like you are told to never use var because the variable can be accessed anywhere, but what does that even mean? Keep reading and hopefully, understand the vocabulary and seeing code examples help. Of course, mess around with code as well.
REASSIGN VS REDECLARE:
When you create a variable, you declare it with the keywords let, var, const
. Reassign means you are giving the variable another value. var
can both be redeclared and reassigned. You will see that it is different for const and let
from this table.
var color = 'blue'; //color declared
color = 'black' //color reassigned
var color = 'pink' //color redeclared
return color
SCOPE:
Var, let, and const have different types of scope. Scope is the context where variables and expressions live.
Types of Scope
-
Global: Variables can be accessed anywhere. A JS document is globally scoped.
var
is globally scoped unless it is declared in a function scope. - Local: Variables in a function scope or block scope are local.
- Lexical: A child scope has access to data in its parent's scope. Think nested functions - inner functions have access to variables of the outer function.
-
Block: Code enclosed in curly brackets
{}
can't be accessed outside the block. Variables declared withlet and const
have block scope. You see the block scopes in if/else statements, for example.var
variables are NOT block scope. -
Function: The variables declared in a function is accessible in that local scope.
var
is used to declare in functions, though you might be told to only uselet
from now on.
//Global Scope
let milkyWay = 'I am globally scoped, so you can access me anywhere!';
{ //Block Scope
var earth = 'Earth';
const sun = 'Sun';
let house = 'My house';
}
console.log(earth) //'Earth'
// console.log(milkyway) //'I am globally scoped, so you can access me anywhere!'
//console.log(house) // will return Error bc house is in block scope
console.log(sun) //will return Error bc sun is in block scope
HOISTING
hoisting means that everytime you declare a variable, Javascript's engine will immediately hoist (or PULL) those variables up in the beginning of the scope and the variables will be declared. But will they be assigned or initialized?
With var, it will be initialized as undefined, while let and const will not. That is why you get an error
Top comments (1)
Simple and objective. Thank you.