menu

JavaScript/Typescript - 16 Topics

DEEP DIVE INTO

JavaScript/Typescript

Topic:var, let and const

menu

In JavaScript, you have three main ways to declare variables: using var, let, and const. These keywords aren't just different ways to say "variable"; they each come with their own rules about where the variable can be accessed (its scope), how JavaScript handles the variable before it's actually written in the code (a concept called hoisting), and whether the variable's value can be changed later (its mutability).  

  Let's dive deeper into understanding var, let, and const:  

var:

  1. Scope: When you declare a variable inside a function using var, that variable is only accessible within that specific function. We call this "function-scoped." However, if you declare a variable with var outside of any function, it becomes a global variable, meaning it can be accessed from anywhere in your JavaScript code.  

  2. Hoisting: JavaScript has a behavior called "hoisting" when it comes to var declarations. Imagine all your var declarations being moved to the very top of their function (or the global scope if declared outside a function) before the code actually runs. This means you can technically refer to a var variable in your code before you've actually written the line where you declare it. However, even though it's accessible, it won't have a value assigned to it yet; it will be initialized with the special value undefined until the line of declaration is reached.

  3. Reassignment: Variables declared with var are quite flexible. You can declare a variable with var, and then later in your code, you can declare another variable with the same name (redeclaration), and you can also change the value that the variable holds (reassignment).

Example:

javascriptfunction example() {
  if (true) {
    var y = 10; // y is function-scoped
  }
  console.log(y); // Outputs: 10
}
example();
console.log(y); // Throws a ReferenceError because y is not defined in the global scope

let:

  1. Scope: When you declare a variable using let, its scope is what we call "block-scoped." Think of a "block" as any section of code enclosed in curly braces {}this could be inside a function, a for loop, an if statement, or just a standalone block. The let variable is only accessible within that specific block of code where it's defined. 

  2. Hoisting: Similar to var, variables declared with let inside a function are also "hoisted," meaning the JavaScript engine is aware of them at the beginning of the function's execution. However, there's a key difference: they aren't automatically given a starting value (like undefined with var). If you try to use a let variable before the line of code where you actually declare it, you'll get a ReferenceError, indicating that the variable hasn't been initialized yet.

  3. Reassignment: Variables declared with let offer a bit more control than const (which we'll discuss later). You can change the value of a let variable after it's been initially assigned. However, you cannot declare another variable with the exact same name within the same scope. This helps prevent accidental overwriting of variables.

Example:

javascriptfunction example() {
  if (true) {
    let y = 10; // y is block-scoped
  }
  console.log(y); // Throws a ReferenceError because y is not defined in this scope
}
example();

const:

  1. Scope: Just like variables declared with let, the scope of variables declared using const is also "block-scoped." This means a const variable is only accessible within the specific block of code (defined by curly braces {}) where it's declared.

  2. Hoisting: Similar to let, const variables are also "hoisted" within their scope. However, and this is important, they are not initialized with any default value. If you attempt to use a const variable before the line of code where you actually declare and assign it a value, you'll run into a ReferenceError.

  3. Reassignment: The key characteristic of const variables is that once you assign a value to them during their declaration, you cannot reassign them to a different value later on. This makes them useful for values that should remain constant throughout your code. However, there's a nuance to remember when dealing with objects and arrays declared with const. While you can't reassign the const variable itself to point to a different object or array, you can still modify the properties of an object or the elements within an array that was declared with const.

Example:

javascriptconst p = 5; // z is block-scoped and cannot be reassigned
p = 10; // Throws a TypeError because you're trying to reassign a const variable

const person = { name: 'Alice' };
person.name = 'Bob'; // Valid, you can modify the object's properties
person = { name: 'Charlie' }; // Throws a TypeError because you're trying to reassign the entire object

In modern JavaScript, it's generally best to use let and const rather than var.

info

If you need to change the value of a variable later in your code, you should declare it using the let keyword. On the other hand, if you intend for a variable to hold a value that should never be changed after its initial assignment, then using const is a good practice. Following this guideline is generally considered best practice in JavaScript. It helps you avoid unexpected side effects and potential bugs in your code by minimizing the number of variables whose values can be altered.

To sum things up, having a clear understanding of how var, let, and const differ in terms of their scope, hoisting behavior, and whether their values can be changed is crucial. Knowing these distinctions will help you write cleaner, better-structured, and easier-to-maintain JavaScript code.

1280 x 720 px