JavaScript Variable Declarations: Var vs. Let vs. Const

JavaScript Variable Declarations: Var vs. Let vs. Const

JavaScript has three main ways to declare variables: var, const and let. Each has its own purpose and rules. In this article, we will explore what they are and when to use each of them. By the end of this guide, you will have a comprehensive understanding of these concepts, enabling you to improve the clarity and efficiency of your code.

Let's start by looking at the table below and dive on each topic:

Differences between var, const and let

Scope

Scope can be defined as the visibility and accessibility of variables, functions and objects.

  • "var" variables have either function or global scope, depending on where it's declared.
  • if declared inside a function it has a function scope meaning it's only accessible inside that function. If accessed outside the function, it will return a ReferenceError saying that the variable is not defined.
  • however, since "var" variables are not block-scoped, this means that a variable declared inside an if block is still accessible outside of that block. This behavior can lead to undesired effects and bugs.
  • if declared outside of any function, it has a global scope meaning it's accessible throughout the code. It also becomes a variable of the global object ("window" in browsers, "global" in Node.js).

var name = "Marco";   // Global scope

function example(){
   var age = 25;   // Function scope

   if(age === 25) {
      var message = "Marco is 25 years old";

      // message is accessible outside the if block, inside the function
      // message is not accessible outside the function
   }

   console.log(message);   // Output: "Marco is 25 years old";
}

example();

console.log(name);   // Output: Marco
console.log(window.name);   // Output: Marco
console.log(age);   // Output: ReferenceError: age is not defined
console.log(message);   // Output: ReferenceError: message is not defined        

  • "let" and "const" variables have block scope. This means that if it's declared inside a block, it's not accessible outside of that block.
  • if accessed outside that block, it will return a ReferenceError saying that the variable is not defined.
  • variables declared with "let" and "const" do not become properties of the global object.

let name = "Marco";

function example(){
   const age = 25;

   if(age === 25){
      let message = "Marco is 25 years old";

      // message is only accessible inside this if block
   }

   console.log(message);   // ReferenceError: message is not defined
}

example();

console.log(name);   // Output: Marco
console.log(window.name);   // Output: undefined
console.log(age);   // ReferenceError: age is not defined
console.log(message);   // ReferenceError: message is not defined        

Re-declarations

Re-declaration is when you declare a variable that has already been declared in the same scope. This can lead to errors and unexpected behavior.

  • "var" variables can be re-declared. This means that re-declaration will not throw an error and it will update the value of the existing variable.

var name = "Marco";
console.log(name);   // Output: Marco

var name = "Filipe";   // Here it is the re-declaration
console.log(name);   // Output: Filipe        

  • "const" and "let" variables can't be re-declared. It will throw a SyntaxError.

let name = "Marco";
console.log(name);   // Output: Marco

let name = "Filipe";   // SyntaxError: "name" has already been declared        

It is considered a good practice to avoid re-declarations. This means that "var" variables should be avoided, prioritizing "let" and "const".

Re-assignment

Re-assignment means assigning a new value to an existing variable.

  • "var" and "let" variables allow re-assignment.

var name = "Marco";
console.log(name);   // Output: Marco

name = "Filipe";   // Re-assignment
console.log(name);   // Output: Filipe        
let name = "Marco";
console.log(name);   // Output: Marco

name = "Filipe";   // Re-assignment
console.log(name);   // Output: Filipe        

  • "const" variables don't allow re-assignment. It will return a TypeError.

const name = "Marco";
console.log(name);   // Output: Marco

name = "Filipe";   // TypeError: Assignment to constant variable        

  • using "const" with arrays and objects is a good practice to avoid acidental re-assignments. While the variable can't be re-assigned, the contents of objects and arrays can still be modified.

const colors = ["Red", "Yellow"];
colors.push("Blue");   // This is allowed
console.log(colors);   // Output: ["Red", "Yellow", "Blue"]

colors = ["Green", "Black"];   // TypeError: Assignment to constant        

Hoisting

Hoisting can be defined as "moving" variables and function declarations to the top of their scope, allowing to use them before they're declared.

Let's focus on "var", "const" and "let" hoisting behaviors:

  • "var" variables are hoisted to the top of their scope. But only the declaration is hoisted, not the initialization.
  • they're initialized with undefined, meaning that it is possible to access and use "var" variables before their declaration as it doesn't produce any error. However, the value will be undefined.

console.log(name);   // Output: undefined
var name = "Marco";        

  • "const" and "let" are also hoisted to the top of their scope but there is no initialization.
  • this means that accessing the variables before their actual declaration will result in an error, in this case a ReferenceError. Meaning that you should first declare the variable and only use it after that.

console.log(name);   // ReferenceError: cannot access name
const name = "Marco";        
console.log(age);   // ReferenceError: cannot access age
let age = 25;        

Resume

Scope

  • "var" variables have function or global scope.
  • "let" and "const" variables have block scope.

Re-declaration

  • "var" variables can be re-declared.
  • "let" and "const" variables can't be re-declared. Attempting to do so will result in a SyntaxError.

Re-assignment

  • "var" and "let" variables can be re-assigned.
  • "const" variables can't be re-assigned. Attempting to do so will result in a TypeError.

Hoisting

  • "var" variables are hoisted to the top of their scope and initialized with undefined.
  • "let" and "const" variables are also hoisted to the top of their scope but are not initialized. Accessing them before initialization will result in a ReferenceError.

Best Practices

  • avoid "var" variables. They can lead to unexpected behaviors and bugs. Prefer "const" or "let".
  • use "const" for variables that don't change.
  • use "let" for variables that need to change.
  • use "const" with objects and arrays. This ensures that the reference to the object or array remains the same while still allowing changes to its contents.

Conclusion

Mastering "var", "const" and "let" declarations in JavaScript is fundamental for writing bug-free and effective code.

By understanding these distinctions, developers can improve code readability, mantainability and avoid common errors and bugs in their JavaScript projects.


Hashtags: #javascript #webdevelopment #var #let #const

Connect with me on X at @CodeWithMarco - https://twitter.com/CodeWithMarco


要查看或添加评论,请登录

Marco Bai?o的更多文章

  • Understanding JavaScript Data Types

    Understanding JavaScript Data Types

    JavaScript is the language that brings websites and web applications to life, making them interactive and dynamic. Data…

  • JavaScript Hoisting and Temporal Dead Zone (TDZ)

    JavaScript Hoisting and Temporal Dead Zone (TDZ)

    Hoisting is a fundamental JavaScript behavior that often intimidates developers. Despite its apparent complexity, it's…

社区洞察

其他会员也浏览了