Var
Var creates a variable that is function-scoped and can be reassigned at any time. If a var variable is declared outside of a function, it is part of the global scope and will be a property on the global object.
Example
//Example 1
var language = "javascript";
language = "JavaScript is the world's most popular programming language"; // New Value Assigned
console.log(language);
//Output
//JavaScript is the world's most popular programming language
//Example 2
function LanguageExample() {
var likes = 500;
console.log(likes); //Output:- 500
}
console.log(likes); //ReferenceError: likes is not defined (we can not access outside the function . only accessible inside function)Let
A variable declared with let can be reassigned at any time. let is block scoped, which means it is only available within the function.
Example
function LanguageExample() {
let likes = 500;
console.log(likes); //Output:- 500
}
console.log(likes); //ReferenceError: likes is not defined (Unable to access outside the function block)const
const is used for constant values. Hence, they cannot be reassigned. They are block scoped, just like let.
Example
// Example 1
const language = "javascript";
language = "JavaScript is the world's most popular programming language"; // Uncaught TypeError: Assignment to constant variable.
//Example 2
function LanguageExample() {
const likes = 500;
console.log(likes); //Output:- 500
}
console.log(likes); //ReferenceError: likes is not defined
Ganesh ChikhalikarPosted Aug 13, 2022, 3:31 AM
Nice article