Skip to Content
Course content

7: Variables: var, let, and const

Click on the "Edit" button in the top corner of the screen to edit your slide content.

One of the first things I see new developers struggle with is the belief that const creates an "immutable" value—basically, that once you declare something as a constant, it is frozen in time and can never, ever change. It sounds logical based on the name, but in JavaScript, that's a dangerous misunderstanding that will lead to some very confusing bugs.

"const means the value is frozen" vs. "const prevents reassignment"

Let me show you exactly where this trips people up. If you assign a string or a number to a const, it does behave like a constant because those are primitive types. But the moment you use an object or an array, the rules change.

const userSettings = { theme: 'dark', notifications: true };

// This is perfectly legal and happens all the time:
userSettings.theme = 'light'; 
console.log(userSettings.theme); // 'light'

// This is what actually triggers the error:
userSettings = { theme: 'light', notifications: false }; 
// TypeError: Assignment to constant variable.

Here is the distinction: const doesn't lock the contents of the object; it locks the binding. I like to think of it as a leash. You can change the dog at the end of the leash (mutate the object properties), but you can't snap the leash and attach it to a completely different dog (reassign the variable).

"var is just an older version of let" vs. "The dangerous unpredictability of var"

You'll see var in plenty of legacy code and older tutorials. You might be tempted to think it's just a synonym for let, but var behaves in ways that feel downright magical—and not the good kind of magic. The biggest culprit is "hoisting" and the lack of block scoping.

if (true) {
  var greeting = "Hello from inside the block!";
}
console.log(greeting); // "Hello from inside the block!"

In the example above, greeting is accessible outside the if block. If I had used let, that console.log would have thrown a ReferenceError. In a large application, having variables "leak" out of their blocks is a recipe for disaster. It makes it incredibly hard to track where a value was actually changed. For this reason, I'll be blunt: stop using var. There is almost no modern scenario where var is the correct choice.

"Just use let for everything" vs. "Defaulting to const for sanity"

Now that we've narrowed it down to let and const, you might wonder why we even need both. Why not just use let for everything since it's more flexible?

It comes down to cognitive load. When I'm reviewing your code, or when you're revisiting a function you wrote six months ago, seeing const tells me something vital: "This variable will always point to the same thing." I don't have to scan the next 50 lines of code to see if that variable gets reassigned to something else. It removes the mental effort of tracking state changes.

My rule of thumb is simple: start with const. If you realize you absolutely must reassign the value—like a counter in a loop or a toggle switch—change it to let. If you find yourself using let everywhere, you're probably mutating state more than you should be.




📋 Practical Task

Fixing the Shopping Cart State Manager

You are maintaining a small shopping cart script. The current code is using var and let incorrectly, causing some unpredictable behavior and making the code harder to read. Your task is to refactor the variables to use the most restrictive declaration possible (preferring const over let, and replacing all var usage).

Requirements:

  • The cart array should never be reassigned to a new array, but items should still be added to it.
  • The taxRate should remain a constant.
  • The totalPrice needs to be updated as items are processed, so it must allow reassignment.
// REFACTOR THIS CODE
var cart = ['Apple', 'Banana'];
var taxRate = 0.07;
let totalPrice = 0;

function addToCart(item) {
  cart.push(item);
  console.log(item + ' added!');
}

function calculateTotal(price) {
  totalPrice = price + (price * taxRate);
  return totalPrice;
}

addToCart('Orange');
console.log('Total: ' + calculateTotal(10));
Rating
0 0

There are no comments for now.

to be the first to leave a comment.