DEV Community

Cover image for Demystifying JavaScript: let, var, and const Explained with Examples
Jack Pritom Soren
Jack Pritom Soren

Posted on

Demystifying JavaScript: let, var, and const Explained with Examples

JavaScript, being a versatile and widely-used programming language, offers several ways to declare variables, namely let, var, and const. Understanding the differences between them is crucial for writing clean, efficient, and bug-free code. In this article, we'll delve into the nuances of let, var, and const, provide clear explanations with examples, and explore real-life scenarios where each is most suitable.

Introduction to let, var, and const

var:

  • var is the traditional way of declaring variables in JavaScript.
  • Variables declared with var have function scope or global scope.
  • They can be re-declared and reassigned.

let:

  • let was introduced in ES6 (ECMAScript 2015) to address some of the issues with var.
  • Variables declared with let have block scope.
  • They can be reassigned, but not re-declared in the same scope.

const:

  • const also came with ES6 and is used to declare constants.
  • Variables declared with const are block-scoped like let.
  • They cannot be reassigned once they are assigned a value. However, for objects and arrays, their properties or elements can be modified.

Understanding with Examples:

var Example:

function varExample() {
    if (true) {
        var message = "Hello";
    }
    console.log(message); // Output: "Hello"
}

varExample();
console.log(message); // Output: "Hello" - var has function scope
Enter fullscreen mode Exit fullscreen mode

let Example:

function letExample() {
    let count = 10;
    if (true) {
        let count = 20;
        console.log(count); // Output: 20
    }
    console.log(count); // Output: 10
}

letExample();
Enter fullscreen mode Exit fullscreen mode

const Example:

function constExample() {
    const PI = 3.14;
    // PI = 3.14159; // Error: Assignment to constant variable
    console.log(PI); // Output: 3.14
}

constExample();
Enter fullscreen mode Exit fullscreen mode

Real-life Examples:

1. Mathematical Constants:

const PI = 3.14;
const E = 2.71;
Enter fullscreen mode Exit fullscreen mode

In mathematical calculations or scientific applications, constants like PI and E are declared using const because their values remain fixed throughout the program.

2. User Authentication Status:

let isAuthenticated = false;
Enter fullscreen mode Exit fullscreen mode

In web development, the authentication status of a user may change based on login/logout actions. Using let allows the status to be updated dynamically.

3. Loop Counters:

for (let i = 0; i < 5; i++) {
    console.log(i);
}
Enter fullscreen mode Exit fullscreen mode

Using let for loop counters ensures that the counter variable is scoped to the loop and doesn't leak to the outer scope.

Conclusion:

Understanding the differences between let, var, and const is fundamental for writing robust JavaScript code. While var has its use cases, let and const provide more predictable behavior and help prevent common bugs. By choosing the appropriate variable declaration based on the requirements of your code, you can write cleaner, more maintainable, and error-resistant JavaScript applications.

Follow me on : Github Linkedin

Top comments (4)

Collapse
 
efpage profile image
Eckehard

While everything you explained was quite correct, it can be helpful to mention, that things might be quite different in some situations.

let a = {}

a.a=10
a.b=20
a.c=a.a*a.b

console.log(a) //-> { a: 10, b: 20, c: 200 }
Enter fullscreen mode Exit fullscreen mode

"a" is an Object, properties can be used as variables, but they do not need to be declared in Javascript.

Things get even stranger if you use Classes:

class c {
  constructor(){
    this.a = 10
    this.b = 20
  }
  mul(){ return this.a * this.b }
}
let OB = new c()
console.log(OB.mul())
Enter fullscreen mode Exit fullscreen mode

Variables inside a class need to be prefixed by "this", but they do not need let or const either. Also, methods (= functions of a class ) do not need to be defined at all, you just write down the name()

Collapse
 
kvetoslavnovak profile image
kvetoslavnovak

What is the point to mix varaiables with properties and methods of an object?

Collapse
 
efpage profile image
Eckehard

The point is the different syntax and the different rules. You cannot - for example - define a constant inside a class. It lies in the history of JS, but is not helpful in any way.

In most other languages you can use the same code in a function or in a class method (= function). In JS you have to rewrite anything, even if you want to do the exact same thing. That is at least confusing.

Collapse
 
eastmann profile image
Maxim Klochkov • Edited

I think you have a mistake in your var Example - message is defined within a function scope so priniting it out in global scope will produce an error:

console.log(message); // message is not defined
Enter fullscreen mode Exit fullscreen mode