Choosing between var, let and const in Javascript

How to choose between var, let and const? The choice between var, let, and const in JavaScript comes down to the desired scope and reassignment behavior of the variable:

  1. var: The var keyword declares a function-scoped or globally-scoped variable. Variables declared with var are hoisted to the top of their scope and can be redeclared. This can potentially introduce bugs and confusion into your code, so it is generally recommended to use let or const in modern JavaScript.

    Example:

    1
    2
    3
    4
    5
    6
    
    var x = 10;
    if (true) {
        var x = 20;  // This redefines the existing 'x'
        console.log(x); // Outputs: 20
    }
    console.log(x); // Outputs: 20, because 'x' is function or globally scoped
    
  2. let: The let keyword declares a block-scoped variable, meaning it is only accessible within the nearest set of curly braces (function, if-else block, or for-loop). It can be reassigned but not redeclared within the same scope.

    Example:

    1
    2
    3
    4
    5
    6
    
    let y = 10;
    if (true) {
        let y = 20;  // This is a new variable local to this block
        console.log(y); // Outputs: 20
    }
    console.log(y); // Outputs: 10, because 'y' inside the if statement does not affect the 'y' outside the block
    
  3. const: The const keyword also declares a block-scoped variable, but once assigned, its value cannot be changed in the same scope, and it cannot be redeclared. This is useful when you want to declare a variable that will always hold the same value, like a constant or a function that will not be redefined.

    Example:

    1
    2
    3
    
    const z = 10;
    // z = 20;  // Uncommenting this line will throw an error, as 'z' cannot be reassigned
    console.log(z); // Outputs: 10
    

In general, if you need to reassign the value of a variable, use let. If you have a value that won’t be reassigned, use const. To avoid potential bugs and code confusion, var is best avoided in modern JavaScript.

Why does Javascript need three different ways to declare a variable when other languages have only one?

JavaScript’s three variable declarations (var, let, and const) have come about as the language has evolved over time, in response to feedback from developers and the needs of increasingly complex applications.

Originally, JavaScript only had var. This was somewhat problematic because var is function-scoped, not block-scoped, which could lead to unexpected behavior, especially for developers coming from other languages where variables are block-scoped.

In the ES6 (also known as ES2015) revision of JavaScript, let and const were introduced to address these issues and to bring more flexibility and clarity to variable declaration:

  • let gives you block scope, which can be helpful in many situations and aligns JavaScript more closely with other C-based languages like Java and C++.

  • const not only provides block scope but also makes the variable constant, which means its value can’t be changed once it’s set. This is useful when you want to make it clear that a variable should not be re-assigned.

It’s also worth noting that many other programming languages do have different ways to declare variables. For example, C++ and Rust have const for constant variables, and Python has global and nonlocal keywords to change variable scope.

So, the existence of var, let, and const in JavaScript can be seen as part of the language’s evolution and its effort to provide developers with more tools to write clear and bug-free code. As a developer, you can choose the most appropriate tool for your particular use case.

Is it correct to say const is used for declaring constants?

Yes, it is correct to say that const is used for declaring constants in JavaScript, but there’s a bit more nuance to it. When you declare a variable with const, you’re saying that the variable identifier cannot be reassigned.

For example:

1
2
const pi = 3.14;
pi = 3.15; // This will throw an error.

However, it’s important to note that when you’re using const with objects or arrays, the contents of the object or array aren’t immutable, only the assignment of the variable is. In other words, the variable always points to the same object or array, but the object or array itself can be changed.

For example:

1
2
3
4
5
6
7
8
const obj = { name: 'John' };
obj.name = 'James'; // This is fine

const arr = [1, 2, 3];
arr.push(4); // This is fine, arr is now [1, 2, 3, 4]

obj = { name: 'Tom' }; // This will throw an error, because we're trying to reassign obj
arr = [1, 2]; // This will throw an error, because we're trying to reassign arr

In this case, while obj and arr are declared with const, and thus cannot be reassigned, the values inside them can still be manipulated. If you need a truly immutable object or array, you would need to use other means (like Object.freeze(), for example).

So primitives will throw an error if reassigned but object will not?

Yes, if you declare a primitive value (like a number, string, boolean) with const, JavaScript will not allow you to reassign it to a new value. Attempting to do so will throw an error.

Here’s an example:

1
2
3
4
5
const num = 10;
num = 20; // Error: "Assignment to constant variable."

const str = 'Hello';
str = 'Goodbye'; // Error: "Assignment to constant variable."

However, if you declare an object or an array with const, you can’t reassign the whole object/array (this would also throw an error), but you can change their properties or elements:

1
2
3
4
5
6
7
8
const obj = { name: 'John' };
obj.name = 'Sarah'; // This is fine, obj is now { name: 'Sarah' }

const arr = [1, 2, 3];
arr[0] = 4; // This is fine, arr is now [4, 2, 3]

obj = { name: 'Bob' }; // Error: "Assignment to constant variable."
arr = [4, 5, 6]; // Error: "Assignment to constant variable."

So, the const keyword in JavaScript protects the binding, not the value. It prevents you from assigning a new value to the variable, but it does not make the value itself immutable.