JavaScript Variables

Home » JavaScript Tutorial » JavaScript Introduction » JavaScript Variables

In programming, a variable is simply a named container for storing a piece of information, or data. Think of it like a label you stick onto a box; you can easily find the box later by reading the label, and you can change what’s inside the box whenever you need to.

Variables are the most fundamental concept in coding because they allow you to manage data, perform calculations, and refer to information later in your program.

Before we look at specific keywords, it is helpful to understand the “Lifecycle” of a variable. There are two distinct steps to creating one:

  • Declaration: This tells the computer, “Please create a container with this specific name.”
  • Assignment: This tells the computer, “Put this specific value inside that container.”
  • Initialization: Doing both steps on a single line.
// 1. Declaration (Creating the box)
let score; 

// 2. Assignment (Filling the box)
score = 10; 

// 3. Initialization (Doing both at once)
// This is the most common way to write code.
let age = 25;
JavaScript
  • const requires you to Initialize (declare + assign) immediately. You cannot leave a const box empty.
  • let and var allow you to Declare now and Assign later.

JavaScript has standard rules for naming variables to make your code consistent and readable:

  • Case-Sensitive: Score and score are treated as two different variables.
  • Start with a letter: Names must start with a letter, underscore (_), or dollar sign ($). They cannot start with a number.
  • Use Camel Case: The universal standard for JavaScript variables is camelCase. Start with a lowercase letter, and capitalize the first letter of subsequent words (e.g., userFirstName, shoppingCartTotal).
  • Avoid Reserved Keywords: You cannot use words that have a special meaning in JavaScript (like const, function, or if).

1. const (The Constant Container)

The const keyword is the most important one and should be your default choice for declaring variables.

  • Use: Use it for anything that should never change, like a fixed tax rate, a person’s name, or a birthday.
  • Rules: The value inside a const container cannot be changed or reassigned after it is first created. It’s constant. const must also be initalized when it’s declared, meaning a value must be assigned to the variable.
    • Note: A const variable’s object or array data assigned to it can be changed or mutated though. const locks the memory reference but doesn’t lock the data assigned to it.
const userName = "Rodney"; // const declared and initialized.
console.log(userName); // Output: Rodney

// If you try to reassign a const variable, JavaScript will throw an error:
//userName = "Alex"; // Uncaught TypeError: Assignment to constant variable.

// Incorrect: This will cause an error because there is no initial value:
// const username;
// userName = "Rodney"; 

// Data assigned to an array can be mutated or changed
// This array has a "4" added to the end of it or "pushed".
const myArray = [1, 2, 3];
myArray.push(4);
console.log(myArray); // Output: [1, 2, 3, 4]
JavaScript

2. let (The Flexible Container)

The let keyword is used for variables whose value you expect to change at some point in your program.

  • Rule: The value inside a let container can be changed or reassigned later.
  • Use: Use it for things that change, like a user’s current score, a count in a loop, or a shopping cart total.
let score = 0; // Initialize score to 0
score = 100; // score is now 100

let greeting = "Hello";
greeting = "Goodbye"; // greeting is now "Goodbye"

// let variables can be declared before being initialized/assigned a value:
let count;
count = 10;
// Above is the same a "let count = 10;"
JavaScript

3. var (The Older Container)

The var keyword is the original way to declare variables in JavaScript.

  • Rule: Like let, the value can be changed, the same let variable examples above can be applied to var.
  • Recommendation: Avoid using var in new code. It has confusing rules related to a concept called scope (which you’ll learn about later) that can lead to bugs. Modern JavaScript development almost exclusively uses const and let. var variable can be reassigned similar to let, but is less secure because of the scope rules associated with it.
  • Scope: var uses Function Scope, meaning it is accessible throughout the entire function, even if declared inside a smaller block like an if statement or a for loop. Both const and let use Block Scope (the better, safer behavior), confining them to the code block ({}) where they are defined. This scope difference is why var is avoided today.

Beginners often confuse these two terms. It is important to know the difference to avoid errors.

  • Reassignment (Changing the Value) This is taking an existing variable and giving it new data.
    • let and var allow this.
    • const forbids this.
  • Redeclaration (Creating the variable again) This is typing the keyword (let, const, var) again with the same name.
    • var allows this (which is bad/confusing).
    • let and const forbid this (which protects your code).
// Redeclaration Example

// WITH VAR (BAD): The computer doesn't complain, it just overwrites it.
var x = 1;
var x = 2; // No error

// WITH LET (GOOD): The computer protects you.
let y = 1;
let y = 2; // SyntaxError: Identifier 'y' has already been declared
JavaScript

When starting a new variable, always try to use const first. If you later find you absolutely need to change the variable’s value, switch it to let. By using const as much as possible, you make your code safer and easier to predict.

Featureconstletvar
Can be Reassigned?NoYesYes
Can be Redeclared?NoNoYes
Requires Initialization?YesNoNo
Scope TypeBlock { }Block { }Function
Best Practice?Use 95% of the time.Use when data changes.Avoid