Scope of var
var declarations are globally scoped or function/locally scoped. It is globally scoped when a var variable is declared outside a function. for example “myText” variable declare outside scope will be available globally.
var myText= "Hello";
function myFunction() {
console.log(myText);
}Hoisting of var
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. so you can declare a variable like below.
function myFunction() {
console.log(myText);
}
var myText= "Hello";Using Let
let is block scoped that means is lines of code bounded by {}.
A block lives in curly braces. Anything within curly braces is a block. So a variable declared in a block with the let is only available for use within that block.
let myLet= "hello";
if (true) {
let myLet= "New Hello ";
console.log(myLet);
//will display " New Hello "
}
console.log(myLet)
//will display "Hello "the difference from var is let can not be redeclared in same scope this will Give ERROR . and you can not use let variable before declaration.
let myLet= "hello 1"; let myLet= "hello new"; console.log(myLet)
Using Const variable
Variables declared with the const maintain constant values. const declarations share some similarities with let declarations.
const declarations are block scoped same as let
const myLet= "hello";
if (true) {
const myLet= "New Hello ";
console.log(myLet);
//will display " New Hello "
}
console.log(myLet)
//will display "Hello "const cannot be updated or re-declared . Below code will give ERROR
const myConst= "Hi"; myConst= "Hello"; //error : Assignment to constant variable.