Do We No Longer Use 'var' in JavaScript?

Yes, in modern JavaScript, the use of var is generally discouraged in favor of let and const.

The var keyword has function scope, meaning it's only available within the function it's declared in. If it's not declared inside any function, it has global scope. This can lead to unexpected behavior if you're not careful.

Let me illustrate this with an example.

function exampleFunction() {
  var functionScoped = "I am function scoped";

  if (true) {
    var supposedToBeBlockScoped = "I am supposed to be block scoped";
  }

  console.log(functionScoped); // Outputs: 'I am function scoped'
  console.log(supposedToBeBlockScoped); // Outputs: 'I am supposed to be block scoped'
}

In this example, supposedToBeBlockScoped is defined inside an if block, but because it's declared with var, it's actually function-scoped to exampleFunction, not block-scoped to the if block. This can be surprising if you're not expecting it.

On the other hand, let and const have block scope, which is more intuitive and less error-prone. let is used when you need to reassign a variable, and const is used when you have a variable that should not be reassigned.

function anotherExampleFunction() {
  let functionScoped = "I am function scoped";

  if (true) {
    let blockScoped = "I am block scoped";
    console.log(blockScoped); // Outputs: 'I am block scoped'
  }

  console.log(functionScoped); // Outputs: 'I am function scoped'
  console.log(blockScoped); // Outputs: ReferenceError: blockScoped is not defined
}

In this example, blockScoped is only available inside the if block where it's declared. If you try to access it outside of that block, even within the same function, you'll get a ReferenceError.

This is usually the behavior developers expect, which is why let and const are generally preferred over var. So, in modern JavaScript code, you'll see let and const used almost exclusively, and var used very rarely, if at all.

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda