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.
Variable Anatomy: Declaration vs. Assignment
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;JavaScriptconstrequires you to Initialize (declare + assign) immediately. You cannot leave aconstbox empty.letandvarallow you to Declare now and Assign later.
Variable Naming Conventions
JavaScript has standard rules for naming variables to make your code consistent and readable:
- Case-Sensitive:
Scoreandscoreare 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, orif).
Declaring Variables: The Three Keywords
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
constcontainer cannot be changed or reassigned after it is first created. It’s constant.constmust also be initalized when it’s declared, meaning a value must be assigned to the variable.- Note: A
constvariable’s object or array data assigned to it can be changed or mutated though.constlocks the memory reference but doesn’t lock the data assigned to it.
- Note: A
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]JavaScript2. 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
letcontainer 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;"JavaScript3. 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 sameletvariable examples above can be applied tovar. - Recommendation: Avoid using
varin 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 usesconstandlet.varvariable can be reassigned similar tolet, but is less secure because of the scope rules associated with it. - Scope:
varuses Function Scope, meaning it is accessible throughout the entire function, even if declared inside a smaller block like anifstatement or aforloop. Bothconstandletuse Block Scope (the better, safer behavior), confining them to the code block ({}) where they are defined. This scope difference is whyvaris avoided today.
Advanced Rules: Reassignment vs. Redeclaration
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.
letandvarallow this.constforbids this.
- Redeclaration (Creating the variable again) This is typing the keyword (
let,const,var) again with the same name.varallows this (which is bad/confusing).letandconstforbid 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 declaredJavaScriptBest Practice: const First
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.
Summary Cheat Sheet
| Feature | const | let | var |
| Can be Reassigned? | No | Yes | Yes |
| Can be Redeclared? | No | No | Yes |
| Requires Initialization? | Yes | No | No |
| Scope Type | Block { } | Block { } | Function |
| Best Practice? | Use 95% of the time. | Use when data changes. | Avoid |




