In JavaScript, let, const, and var are used to declare variables, but they are different in three ways:
1. Scope
2. Reassignment
3. Hoisting
var is a functional scope means we access var variable anywhere within the function if we try access it outside function it will show error undefined
Example:-
function demo(){ if(true){ var n = 3; } console.log(n) } console.log(n) //ReferenceError: n is not defined demo();
let & const are block means we can access them within the scope only otherwise it will show undefined error
Example:-
function demo(){ if(true){ let n = 3; const m = 5; console.log(n) // 3 console.log(m) // 5 } console.log(n) //ReferenceError: n is not defined console.log(m) //ReferenceError: n is not defined } console.log(n) //ReferenceError: n is not defined console.log(m) //ReferenceError: n is not defined demo();
// var example console.log(a); // undefined (due to hoisting) var a = 10; console.log(a); // 10 // let example console.log(b); // ReferenceError: Cannot access 'b' before initialization let b = 20; console.log(b); // 20 // const example const c = 30; c = 40; // TypeError: Assignment to constant variable
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3