im sure this question crossed your mind , what is the difference between var , let & const
in short here is the difference :
if you want to learn more on why , here is the full explanation :
lets start with var :
var num = 500;
Before ES6, var declarations ruled. There are many issues associated with variables declared with var, though. That is why it was necessary for new ways to declare variables to emerge. First, let's get to understand var more before we discuss those issues.
the scope here means where these variables are available for use. var declarations are globally scoped or function/locally scoped.
The scope is global when a var variable is declared outside a function. This means that any variable that is declared with var outside a function block is available for use in the whole window.
var is function scoped when it is declared within a function. This means that it is available and can be accessed only within that function.
Want to learn more about scope ? i suggest this course from Linkedin learning
in ES2015 (or ES6) we were introduced two new ways to create variables, let and const. But before we actually dive into the differences between var, let, and const, first let me answer a question that i already see coming ,
Why is it adding new keywords like let instead of updating?
You might wonder why JS introduced let instead of improving the existing var keyword. The answer is simple: It is done to keep backward compatibility. You wouldn’t want to break the web, would you?
there are some prerequisites you need to know first. They are :
- variable declarations
- function scope vs Block-scope
Variable Declaration vs Initialization A variable declaration introduces a new identifier.
var NewDeclaration console.log(NewDeclaration) // log undefined
So if we log the declaration variable, we get undefined.
In contrast to variable declaration, variable initialization is when you first assign a value to a variable.
console.log(NewDeclaration) // logs undefined NewDeclaration = 'This is an initialization'
So here we’re initializing the declaration variable by assigning it to a string.
This leads us to our second concept, Scope.
What is Scope? Simply put , Scope is the accessibility of variables, functions, and objects in some particular part of your code during runtime. In other words, scope determines the visibility of variables and other resources in areas of your code.
- Global Scope
- Local Scope
Other types include;
Block Scope Lexical Scope Global Scope This scope which is the default defines all variables as universal such that every part of the program can access them.
(To be continued)