Catalin Vasile

I'm a design-focused engineer.

JavaScript Bits: Understanding var vs let vs const

In this guide, we’ll explore in depth how the var, let and const keywords work in ES6+. We’ll take each of them apart, see how they work and how we can use them.

TLDR

Here’s a quick summary if you’re on the run:

  • In the quick descriptions below, being “reassignable” is not equal to being “mutable”. It simply means that once a variable is defined, you can’t assign something else to it.
  • If you’re using ES6+, simply avoid using var. It’s confusing whether it will be reassigned or not just by looking at it.
  • Using let you can define a property that can be reassigned. Also, its scope is being limited to the block where it’s used.
  • Using const you can define a property that cannot be reassigned. Similarly to let, its scope is also limited to the block where it’s used.

Using var

The var keyword allows you to declare a variable and optionally, initialize its value. It’s important to make the distinction between declaration and initialization properly.

Let’s take a look at an example and analyze it in more depth:

var firstName = 'John';     // Declared and initialized a value.
var lastName;               // Just declared. Value is `undefined`.

Hoisting

Any var declaration is hoisted. This means that any variable declaration is processed before any code is executed.

name = 'John';
var name;

// The example above is the same as writing:
var name;
name = 'John';

Keep in mind that hoisting in this case is isolated at a declaration level, not initialization.

console.log(name); // `undefined` as it's not initialized yet.

var name = 'John';

Scope

The scope of a variable declared with var is its current execution context.

This can be either its enclosing function or the global scope. Undeclared variables are global by default.

It’s recommended to always declare variables first before using them, regardless of scope. Not doing so, will most probably lead to unexpected results.

function getName() {
    name = 'John';                // This will throw an error in strict mode.
    return name;
}

var name = getName();             // John

console.log(name);                // John
console.log(this.name);           // John
console.log(this.name === name);  // true

Using let

The let keyword allows you to declare a block scope local variable and optionally initialize its value.

💡Fun fact: If you’re wondering why they chose let as a keyword instead of something else, it’s because it has a mathemathical background (eg. “let x be 1”).

In terms of scope, the difference between let and var is that let variables have their scope in the block or sub-block in which they are defined. On the other hand, var variables have their scope in the entire function’s scope.

For example, if you declare a variable using let inside an if block and one outside, you have declared two different variables.

let name = 'John';

if (name === 'John') {
    console.log(name);      // undefined
    let name = 'Catalin';
    console.log(name);      // Catalin
}

console.log(name);          // John

The following is an example of how var works inside a function. It’s a really bad example, but it makes the point. Please don’t redeclare variables in real-world code.

function getName(userId) {
  var name = 'Placeholder Name';

  if (userId === 1) {
    var name = 'Catalin';  // 🙅‍♀️ Bad practice: will throw in strict mode.
  }

  console.log(name);       // If the userId is 1, the name will be `Catalin`.

  return name;
}

getName();                 // `Placeholder Name`
getName(1);                // `Catalin`

Using const

Once a variable is declared and initialized using the const keyword, it cannot be re-assigned to something else. In simple terms, using const makes a variable read-only. This does not mean that the value is purely immutable.

In terms of scope, const variables are also block-scoped similarly to let.

const name = 'Catalin';

name = 'John';          // TypeError: Assignment to constant variable.

Let’s also confirm using code that variables declared using const are not purely immutable.

const user = {
    name: 'Catalin'
};

user.name = 'John';

console.log(user);      // { "name": "John" }

Conclusion

That’s it! I hope you enjoyed this short article on how var, let and const work in JavaScript. Is there something that I’ve missed? Please let me know your thoughts in the comments below. 😄

Subscribe

Be the first to know when I publish a new article on the blog.

No spam. You can unsubscribe at any time.


Comments