The difference between let, var and const JavaScript Keywords
The difference between let, var and const JavaScript Keywords
let, var and const keywords are used to declare variables
let text="Africa"
var number=1000000000
const array=[1,2,3]
Before ES6, only the var keyword existed as a way to declare variables in JavaScript.
The newer let and const keywords were introduced in ES6 as alternative ways to declare variables.
Variables declared with let and var keywords can be reassigned to other values at runtime
let text="Africa"
var number=10000000
text="Asia"
number=11111111
The const keyword is used to declare constant varibles, this means that variables declared with the const keyword cannot be reassigned to other values at runtime, For example, the following code will throw a "TypeError:Assignment to constant variable" syntax Error because we have reassigned the constant array variable to a new array value
const array=[1,2,3]
array=["a", "b", "c"]
A block of code refers to the body of classes, loops, functions and conditional statements; usually enclosed in curly braces "{}". Variables declared with let and const keywords are locally scoped to a block of code in which they are created. The following code snippet will throw a "ReferenceError: count is not defined" syntax error because we have referenced variable "count" outside the "if" statement's local scope
for (let count=0; count<5; count+=1){
console.log(count)
}
console.log("Final: " + Str(count))
On the other hand, variables declared with the var keyword are locally scoped within the function in which they are created or globally scoped when created elsewhere. The code snippet below will execute successfully because the variable "count" is globally scoped
for (var count=0; count<5; count+=1){
console.log(count)
}
console.log("Final: " + String(count))