JavaScript Fundamentals: Variables (var, let, const)

Welcome to the second part of our Node.js Jumpstart series! Before diving deeper into Node.js specifics, it's essential to have a solid understanding of the JavaScript language itself. One of the first things you'll do in any programming language is work with variables to store data. JavaScript gives you three keywords to declare variables: var, let, and const. Let's see how they work and which ones you should use.

TLDR

If you have the attention span of a distracted squirrel (like me, thanks to YouTube Shorts and Reels), here’s the quick survival guide:

  • var: The Wild West of JavaScript. Declares variables globally or function-scoped (never block-scoped), and happily lets you redeclare the same variable without even a passive-aggressive warning. Perfect for time travelers who enjoy debugging ancient issues from 2009... so the old legends say, because honestly, that was before my time.
  • let: The responsible middle child. Block-scoped (so actually matters), allows reassignment, but doesn't let you redeclare within the same block. Works well for values that need to change like loop counters, user inputs, or your will to live during long sprints.
  • const: A sacred blood oath: the binding promise that the variable identifier will not be reassigned. (But careful: if the const points to an object or array, you can still mutate its internals and trigger late-night existential crises.)

If you want to prove you're better than the average developer who just copy-pastes from Stack Overflow ChatGPT (or whatever new child of Skynet they launched this month) without blinking, keep reading.

Or if you really just want to skip straight to the Modern Best Practices, scroll to the bottom. I won’t be offended. Probably.


JavaScript Variables: var, let, and const

Variables are like containers for storing information. You give them a name, and they hold a value.

let message = "Hello, World!";
let count = 10;
let isEnabled = true;
let user = { name: "Alice" };
let colors = ["red", "green", "blue"];

JavaScript has evolved, and the way we declare variables has changed.

1. var (The Old Way)

Before 2015, var was the only way to declare variables. It has some behaviors that can be surprising:

  • Function Scope: Variables declared with var are scoped to the nearest function block, not to if blocks or for loops.
  • Hoisting: Declarations (but not assignments) are "hoisted" to the top of their scope, meaning you can use a var variable before it's declared in the code, but its value will be undefined.
function greet() {
  var greeting = "Hello";
  if (true) {
    var message = greeting + " World"; // 'message' is scoped to the function, not the if block
    console.log(message); // Output: Hello World
  }
  console.log(message); // Output: Hello World (message is still available here!)
}
greet();

console.log(hoistedVar); // Output: undefined (declaration is hoisted)
var hoistedVar = 10;
console.log(hoistedVar); // Output: 10

Due to its surprising scoping and hoisting behavior, var is less predictable and is generally discouraged in modern JavaScript.

2. let (The Modern Way for Reassignable Variables)

Introduced in ECMAScript 2015 (ES6), let is the modern standard for variables whose values might change.

  • Block Scope: Variables declared with let are scoped to the nearest enclosing block ({}), including if blocks, for loops, etc.
  • No Re-declaration: You cannot declare a let variable with the same name in the same scope.
  • Temporal Dead Zone: let variables are not hoisted in the same way as var. Accessing a let variable before its declaration in the code will result in a ReferenceError.
function greetModern() {
  let greeting = "Hello";
  if (true) {
    let message = greeting + " World"; // 'message' is scoped ONLY to this if block
    console.log(message); // Output: Hello World
  }
  // console.log(message); // 🚫 ERROR: message is not defined outside the if block
}
greetModern();

// console.log(hoistedLet); // 🚫 ERROR: Cannot access 'hoistedLet' before initialization (Temporal Dead Zone)
let hoistedLet = 20;
console.log(hoistedLet); // Output: 20

let count = 1;
count = 2; // ✅ You can reassign let variables
// let count = 3; // 🚫 ERROR: 'count' has already been declared

let is much more predictable due to its block scoping. Use it when you know the variable's value needs to change.

3. const (The Modern Way for Variables That Don't Need Reassignment)

Also introduced in ES6, const is for variables that are assigned a value once, and that assignment cannot be changed later.

  • Block Scope: Like let, const is block-scoped.
  • Must Be Initialized: You must assign a value to a const variable when you declare it.
  • Cannot Be Reassigned: The variable name cannot be pointed to a new value after its initial assignment.
const name = "Alice";
// name = "Bob"; // 🚫 ERROR: Assignment to constant variable.

const PI = 3.14159;
// const gravity; // 🚫 ERROR: Missing initializer in const declaration

IMPORTANT NOTE: const does NOT make the value immutable, only the assignment.

const user = { name: "Alice", age: 30 };
user.age = 31; // ✅ This is allowed! You are changing a property *of* the object, not reassigning 'user' itself.
console.log(user); // Output: { name: 'Alice', age: 31 }

const colors = ["red", "green"];
colors.push("blue"); // ✅ This is allowed! You are modifying the array, not reassigning 'colors'.
console.log(colors); // Output: [ 'red', 'green', 'blue' ]

const is excellent for variables whose reference should not change (like function references, configuration values, imported modules, or object/array references you intend to modify internally but not replace).

Modern Best Practice:

In modern JavaScript and Node.js, the widely accepted best practice is to:

  • Use const by default. If the variable's value will never be reassigned after its initial declaration, use const. This signals intent and prevents accidental reassignments, making your code safer and easier to reason about.
  • Use let only when you know you need to reassign the variable's value later in the code (e.g., loop counters, variables that change state).
  • Avoid var completely in new code.

Choosing the right keyword (const or let) makes your code clearer and helps prevent bugs. Get into the habit of using const as your default!

In JavaScript, var, let, and const aren’t just different spellings; picking the right one is the difference between sleeping peacefully and getting a 3 a.m. production outage call because someone overwrote a value they shouldn’t have.

Now that you know how to declare variables, let's look at how to define reusable blocks of code using Functions in the next article.