Var, Let, And Const Differences In JavaScript

Var

Var creates a function-scoped variable that can be reassigned at any time. Var variables go within the global scope and become properties of the global object if they are defined outside of a function.

Example
//Example 1
var languageName = "javascript";
languageName = "JavaScript is the world's most popular programming language"; // Assigned New Value
console.log(languageName);
//Output
//JavaScript is the most widely used programming language worldwide
//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

Anytime after being defined with let, a variable may be reassigned. Let is available just inside the function since it is block scoped.

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

Constant values are expressed using const. As a result, they cannot be changed. Like let, they are block scoped.

Example
// Example 1
const languageName = "javascript";
languageName = "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

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories