Ritim İstanbul A5 Blok No: 46, D: 112, 34846 Maltepe/İstanbul

JavaScript var vs let variables: What’s the difference?

JavaScript is a popular and versatile programming language that powers many web applications. However, it also has some quirks and pitfalls that can confuse or frustrate developers. One of these is the difference between var and let variables, which are two ways of declaring variables in JavaScript.

JavaScript var vs let

In this blog post, we will explore the difference between var and let variables, how they affect the scope, hoisting, and redeclaration of variables, and why you should prefer let over var in most cases. We will also look at some examples and common scenarios where the difference between var and let matters. By the end of this post, you will have a better understanding of how to use var and let variables correctly and avoid potential bugs in your code.

Why we use variables in JavaScript?

Variables are containers for storing data in JavaScript. They allow us to reuse values, perform calculations, and manipulate data. Variables also make our code more readable and meaningful by giving names to the data we use. For example, instead of writing 4 + 27, we can write initialApples + applesBought, which tells us what the numbers represent.

There are different ways of declaring variables in JavaScript, such as var, let, and const. Each one has its own scope, hoisting, and redeclaration behavior. You can learn more about the difference between var and let in this blog post or this web page.

Difference between var and let variables

The main difference between JavaScript var and let is the scope of the variables they create. Variables declared by var are function scoped, meaning they are available throughout the function in which they are declared. Variables declared by let are block scoped, meaning they are only available inside the block where they are defined, such as a loop or an if statement. This affects how the variables are hoisted, redeclared, and accessed in different scopes.

For example, consider the following code:

function run() {
  var foo = "Foo";
  let bar = "Bar";

  console.log(foo, bar); // Foo Bar

  {
    var moo = "Mooo";
    let baz = "Bazz";

    console.log(moo, baz); // Mooo Bazz
  }

  console.log(moo); // Mooo
  console.log(baz); // ReferenceError
}

run();

In this code, the variables foo and bar are declared by var and let respectively in the function scope. They are both accessible inside the function run. The variables moo and baz are declared by var and let respectively in the block scope. They are only accessible inside the block denoted by { }. However, the variable moo is also hoisted to the function scope, meaning it can be accessed outside the block as well. The variable baz is not hoisted, meaning it cannot be accessed outside the block where it is defined. Trying to do so will result in a ReferenceError.

Another example is the following code:

var funcs = [];

// let's create 3 functions
for (var i = 0; i < 3; i++) {
  // and store them in funcs
  funcs[i] = function() {
    // each should log its value.
    console.log("My value: " + i);
  };
}

for (var j = 0; j < 3; j++) {
  // and now let's run each one to see
  funcsj;
}

In this code, the variable i is declared by var in the for loop. It is function scoped, meaning it is shared by all the functions stored in the funcs array. When the functions are invoked, they all log the same value of i, which is 3, the final value of the loop. This is not the intended behavior, as we would expect each function to log its own value of i.

If we replace var with let in the for loop, the code will work as expected. This is because let is block scoped, meaning each iteration of the loop will have its own variable i. When the functions are invoked, they will log the correct value of i, which is 0, 1, and 2 respectively.

var funcs = [];

// let's create 3 functions
for (let i = 0; i < 3; i++) {
  // and store them in funcs
  funcs[i] = function() {
    // each should log its value.
    console.log("My value: " + i);
  };
}

for (var j = 0; j < 3; j++) {
  // and now let's run each one to see
  funcsj;
}

Output:

My value: 0
My value: 1
My value: 2

For more information, you can check out these web pages:

More blogs

What ‘data’ element used for in HTML?

HTML is a markup language that allows us to create web pages with different types of content. However, not all content is equally understandable...

Is it possible to connect Google Sheets with JavaScript?

The fusion of web development and data management has become crucial for efficient workflow and innovative solutions. One such powerful combination is the integration...

Automatically inserting current dates into HTML elements with JavaScript

In today's blog post, we're going to explore a useful JavaScript code snippet that allows you to automatically insert the current date into specific...

How to add the current date automatically to HTML with JavaScript?

In web development, it's often necessary to display the current date on a webpage. Whether you're building a blog, an e-commerce site, or a...

What is Swiper JS and how to use it?

Swiper JS is a powerful and versatile library that allows you to create stunning and interactive web pages and apps with touch-friendly sliders, carousels,...

Splitting paragraphs into sentences in Google Sheets with a custom function

Google Sheets sometimes lacks the precise functions we require. However, the application offers a remedy in the form of "Apps Script," enabling the creation...

More from the blog

What ‘data’ element used for in HTML?

HTML is a markup language that allows us to create web pages with different types of content. However, not all content is equally understandable...

Is it possible to connect Google Sheets with JavaScript?

The fusion of web development and data management has become crucial for efficient workflow and innovative solutions. One such powerful combination is the integration...

Automatically inserting current dates into HTML elements with JavaScript

In today's blog post, we're going to explore a useful JavaScript code snippet that allows you to automatically insert the current date into specific...

How to add the current date automatically to HTML with JavaScript?

In web development, it's often necessary to display the current date on a webpage. Whether you're building a blog, an e-commerce site, or a...