Last modified: May 26, 2026

JavaScript Basics Variables

Variables are the building blocks of JavaScript. They store data values. Think of them as labeled boxes. You put data inside. You use the label to get it back. Mastering variables is your first step in coding.

This guide covers everything a beginner needs. We will look at declaration, assignment, scope, and types. We will also explore naming rules and best practices. By the end, you will write clean variable code.

What Is a Variable?

A variable is a container for data. It holds a value. That value can change later. In JavaScript, we use keywords to create them. The three main keywords are var, let, and const.

Every variable has a name. You choose the name. It must follow specific rules. We will cover those soon. Variables make your code dynamic and reusable.

Declaring Variables with let

The modern way to declare a variable is with let. It was introduced in ES6. Use let when the value might change later. It has block scope. This means it only exists inside the curly braces {} where you define it.


// Declare a variable with let
let userName = "Alice";
console.log(userName); // Output: Alice

// Change the value
userName = "Bob";
console.log(userName); // Output: Bob

Alice
Bob

Notice we can reassign userName. That is allowed with let. But you cannot redeclare the same let variable in the same scope. This prevents errors.


let age = 25;
let age = 30; // Error! Cannot redeclare let variable

Declaring Variables with const

Use const for values that should not change. It stands for constant. Once assigned, you cannot reassign it. However, if the value is an object or array, you can modify its properties. The binding is constant, not the value itself.


// Declare a constant
const birthYear = 1990;
console.log(birthYear); // Output: 1990

// This will cause an error
birthYear = 1995; // Error! Assignment to constant variable

// But with objects, properties can change
const person = { name: "Alice" };
person.name = "Bob"; // This is allowed
console.log(person.name); // Output: Bob

1990
Bob

Always use const by default. Only use let when you know the variable must change. This makes your code safer and easier to understand.

The Old var Keyword

Before ES6, var was the only way. It still works, but avoid it in modern code. var has function scope, not block scope. This can lead to bugs. It also allows redeclaration, which is confusing.


var x = 10;
var x = 20; // No error with var
console.log(x); // Output: 20

20

Because var is function-scoped, it can leak out of blocks like if or for. This is why let and const are preferred. For a deeper look, read our JavaScript Variable Declaration Guide.

Naming Rules for Variables

Variable names must follow rules. They can contain letters, digits, underscores (_), and dollar signs ($). They cannot start with a digit. They are case-sensitive. So myVar and myvar are different.

Use camelCase for multi-word names. Start with a lowercase letter. For example: firstName, totalPrice. This is a common JavaScript convention.

Reserved words like if, for, let cannot be used as variable names. Choose descriptive names. This makes your code self-documenting.


// Good variable names
let firstName = "John";
let itemCount = 5;
let _privateVar = true;
let $dollar = 100;

// Bad variable names
let 1stPlace = "gold"; // Error: starts with digit
let if = "condition"; // Error: reserved word

Variable Scope Explained

Scope determines where a variable is accessible. There are three main scopes: global, function, and block. Global scope means the variable is available everywhere. Function scope means it is only inside a function. Block scope means it is only inside a block like {}.

With let and const, variables are block-scoped. With var, they are function-scoped. This difference is crucial. For more details, see our JavaScript Variable Scope Explained guide.


// Block scope example with let
if (true) {
    let blockVar = "I am inside block";
    console.log(blockVar); // Works
}
console.log(blockVar); // Error! blockVar is not defined

// Function scope example with var
function test() {
    var functionVar = "Inside function";
}
console.log(functionVar); // Error! functionVar is not defined

Variable Types in JavaScript

JavaScript is dynamically typed. You do not declare the type. The type is determined by the value. There are primitive types and object types. Primitive types include string, number, boolean, null, undefined, symbol, and bigint.

Objects include arrays, functions, dates, and plain objects. You can check the type with the typeof operator. This is helpful for debugging.


let name = "Alice";        // string
let age = 30;               // number
let isStudent = true;       // boolean
let car = null;             // null
let job;                    // undefined

console.log(typeof name);   // "string"
console.log(typeof age);    // "number"
console.log(typeof isStudent); // "boolean"
console.log(typeof car);    // "object" (known quirk)
console.log(typeof job);    // "undefined"

string
number
boolean
object
undefined

Understanding types helps avoid bugs. For a complete reference, check our JavaScript Variable Types Guide.

Variable Hoisting

Hoisting is a JavaScript behavior. Declarations are moved to the top of their scope. But only the declaration, not the initialization. With var, the variable is hoisted and initialized as undefined. With let and const, they are hoisted but not initialized. Accessing them before declaration gives a ReferenceError.


// var hoisting
console.log(hoistedVar); // Output: undefined
var hoistedVar = "I am hoisted";

// let hoisting (Temporal Dead Zone)
console.log(hoistedLet); // Error! Cannot access before initialization
let hoistedLet = "Not hoisted like var";

undefined
ReferenceError: Cannot access 'hoistedLet' before initialization

This is why you should declare variables at the top of their scope. It makes your code predictable and easier to read.

Best Practices for Variables

Follow these tips to write clean JavaScript. Use const by default. Only use let when reassignment is needed. Avoid var entirely. Use descriptive names. Keep names concise but meaningful.

Declare one variable per line. This improves readability. Initialize variables when you declare them. Avoid global variables. They can cause conflicts. Use block scope to limit visibility.


// Good practice
const maxUsers = 100;
let currentUser = "Alice";
let loginAttempts = 0;

// Bad practice
var x = 10;
var y = 20;
var z = 30; // Hard to read and maintain

Always use strict mode by adding "use strict" at the top of your scripts. This catches common errors. It also prevents accidental global variables.

Example: Full Program

Let us put everything together. This program uses variables to calculate a simple discount. It shows const, let, and type conversion.


// Full example: Discount calculator
"use strict";

const TAX_RATE = 0.08; // Constant tax rate
let itemPrice = 50;    // Price in dollars
let quantity = 3;      // Number of items

// Calculate total before tax
let subtotal = itemPrice * quantity;
console.log("Subtotal: $" + subtotal); // Output: Subtotal: $150

// Calculate tax amount
let taxAmount = subtotal * TAX_RATE;
console.log("Tax: $" + taxAmount); // Output: Tax: $12

// Calculate final total
let total = subtotal + taxAmount;
console.log("Total: $" + total); // Output: Total: $162

Subtotal: $150
Tax: $12
Total: $162

Notice we used const for the tax rate. It never changes. We used let for values that change during calculation. This makes the code clear and safe.

Conclusion

Variables are essential in JavaScript. You now know the three keywords: let, const, and var. Use const most of the time. Use let for values that change. Avoid var.

You learned about naming rules, scope, hoisting, and types. These concepts will help you write better code. Practice by creating your own variables. Experiment with different types.

For more examples, explore our JavaScript Variables Examples page. Keep coding and soon variables will feel natural.