Programming Languages

JavaScript Variables Tutorial: Complete Guide with Examples

Master JavaScript from basics to advanced concepts with this comprehensive beginner-friendly guide covering syntax, functions, objects, and real-world applications.

Published August 16, 2025
12 min read
beginner
by RuneHub Team

JavaScript Variables Tutorial: Complete Guide with Examples

Variables are the foundation of JavaScript programming, acting as containers that store data values for use throughout your applications. Understanding how to properly declare, initialize, and manage variables is crucial for writing effective JavaScript code. This tutorial covers everything you need to know about JavaScript variables, from basic declarations to advanced concepts like scope and hoisting.

Table of Contents

  1. Variable Declaration Methods
  2. Variable Initialization and Assignment
  3. Scope and Accessibility Rules
  4. Hoisting Behavior and Implications
  5. Best Practices and Common Patterns

Variable Declaration Methods

JavaScript provides three primary ways to declare variables, each with distinct characteristics and use cases.

The var Declaration

The var keyword was the original method for declaring variables in JavaScript, with function-level scoping and hoisting behavior.

javascript
var userName = "John";
var age = 25;
var isActive; // undefined by default

console.log(userName); // "John"
console.log(age); // 25
console.log(isActive); // undefined

Variables declared with var can be redeclared and updated within the same scope:

javascript
var message = "Hello";
var message = "Hi there"; // Redeclaration allowed
message = "Welcome"; // Update allowed

console.log(message); // "Welcome"

The let Declaration

Introduced in ES6, let provides block-level scoping and prevents common issues associated with var.

javascript
let productName = "Laptop";
let price = 999.99;
let inStock = true;

console.log(productName); // "Laptop"
console.log(price); // 999.99
console.log(inStock); // true

Unlike var, let prevents redeclaration in the same scope but allows updates:

javascript
let counter = 0;
// let counter = 1; // SyntaxError: Identifier 'counter' has already been declared
counter = 10; // Update allowed

console.log(counter); // 10

The const Declaration

The const keyword creates constants that cannot be reassigned after declaration, also with block-level scoping.

javascript
const API_URL = "https://api.example.com";
const MAX_USERS = 100;
const CONFIG = {
    theme: "dark",
    language: "en"
};

console.log(API_URL); // "https://api.example.com"
console.log(MAX_USERS); // 100

Constants must be initialized at declaration and cannot be reassigned:

javascript
const PI = 3.14159;
// PI = 3.14; // TypeError: Assignment to constant variable

// const radius; // SyntaxError: Missing initializer in const declaration

However, object and array contents can still be modified:

javascript
const user = { name: "Alice", age: 30 };
user.age = 31; // Allowed - modifying object property
user.city = "New York"; // Allowed - adding new property

console.log(user); // { name: "Alice", age: 31, city: "New York" }

Variable Initialization and Assignment

Variables can be declared and initialized in various ways, depending on your specific needs.

Declaration Without Initialization

Variables can be declared without immediate assignment, receiving an undefined value:

javascript
let userName;
var userAge;

console.log(userName); // undefined
console.log(userAge); // undefined

Multiple Variable Declaration

You can declare multiple variables in a single statement for cleaner code:

javascript
let firstName = "John", lastName = "Doe", age = 25;
var x, y, z = 10;

console.log(firstName); // "John"
console.log(lastName); // "Doe"
console.log(z); // 10
console.log(x); // undefined

Dynamic Assignment and Type Flexibility

JavaScript variables are dynamically typed, meaning they can hold different data types:

javascript
let dynamicVar = "Hello"; // String
console.log(typeof dynamicVar); // "string"

dynamicVar = 42; // Number
console.log(typeof dynamicVar); // "number"

dynamicVar = true; // Boolean
console.log(typeof dynamicVar); // "boolean"

dynamicVar = { name: "Object" }; // Object
console.log(typeof dynamicVar); // "object"

Scope and Accessibility Rules

Understanding variable scope is essential for preventing bugs and writing maintainable code.

Global Scope

Variables declared outside any function or block have global scope and are accessible everywhere:

javascript
var globalVar = "I'm global";
let globalLet = "Also global";
const GLOBAL_CONST = "Global constant";

function testAccess() {
    console.log(globalVar); // Accessible
    console.log(globalLet); // Accessible
    console.log(GLOBAL_CONST); // Accessible
}

testAccess();

Function Scope

Variables declared with var inside functions are function-scoped:

javascript
function calculateTotal() {
    var tax = 0.08; // Function-scoped
    let subtotal = 100; // Also function-scoped
    
    if (subtotal > 50) {
        var discount = 10; // Still function-scoped
        let shipping = 5; // Block-scoped
    }
    
    console.log(tax); // 0.08
    console.log(discount); // 10 - accessible due to var
    // console.log(shipping); // ReferenceError - block-scoped with let
}

Block Scope

Variables declared with let and const are limited to their containing block:

javascript
if (true) {
    let blockLet = "Block scoped";
    const BLOCK_CONST = "Also block scoped";
    var functionVar = "Function scoped";
}

// console.log(blockLet); // ReferenceError
// console.log(BLOCK_CONST); // ReferenceError
console.log(functionVar); // "Function scoped" - accessible

Practical Scoping Example

Here's how different scoping rules work in practice:

javascript
function processOrder(items) {
    const TAX_RATE = 0.08; // Function-scoped constant
    let total = 0; // Function-scoped variable
    
    for (let i = 0; i < items.length; i++) { // Block-scoped loop variable
        let itemPrice = items[i].price; // Block-scoped
        total += itemPrice;
    }
    
    // console.log(i); // ReferenceError - i is block-scoped
    // console.log(itemPrice); // ReferenceError - itemPrice is block-scoped
    
    let tax = total * TAX_RATE; // Function-scoped
    return total + tax;
}

Hoisting Behavior and Implications

Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their scope.

var Hoisting

Variables declared with var are hoisted and initialized with undefined:

javascript
console.log(hoistedVar); // undefined (not ReferenceError)
var hoistedVar = "Now I have a value";
console.log(hoistedVar); // "Now I have a value"

// The above code behaves like this:
// var hoistedVar; // Declaration hoisted
// console.log(hoistedVar); // undefined
// hoistedVar = "Now I have a value"; // Assignment stays in place

let and const Hoisting

Variables declared with let and const are hoisted but not initialized, creating a "temporal dead zone":

javascript
// console.log(letVar); // ReferenceError: Cannot access 'letVar' before initialization
let letVar = "I'm a let variable";

// console.log(constVar); // ReferenceError: Cannot access 'constVar' before initialization
const constVar = "I'm a const variable";

Practical Hoisting Example

Understanding hoisting helps avoid common pitfalls:

javascript
function demonstrateHoisting() {
    console.log("Before declarations:");
    console.log(typeof varVariable); // "undefined"
    // console.log(typeof letVariable); // ReferenceError
    
    var varVariable = "var value";
    let letVariable = "let value";
    
    console.log("After declarations:");
    console.log(varVariable); // "var value"
    console.log(letVariable); // "let value"
}

Best Practices and Common Patterns

Following established patterns and best practices leads to more maintainable and bug-free code.

Modern Variable Declaration Guidelines

Use these guidelines for choosing the right declaration method:

javascript
// Prefer const for values that won't be reassigned
const API_ENDPOINT = "https://api.example.com";
const users = []; // Array contents can still be modified

// Use let for variables that will be reassigned
let currentUser = null;
let attempts = 0;

// Avoid var in modern JavaScript
// var oldStyle = "deprecated pattern";

Descriptive Naming Conventions

Choose clear, descriptive names that communicate purpose:

javascript
// Good: Descriptive and clear
const MAX_RETRY_ATTEMPTS = 3;
let isUserLoggedIn = false;
let currentTemperature = 72.5;
const userPreferences = { theme: "dark", notifications: true };

// Avoid: Unclear or abbreviated
// const MAX = 3;
// let flag = false;
// let temp = 72.5;

Common Variable Patterns

Here are frequently used patterns for different scenarios:

javascript
// Configuration objects
const appConfig = {
    apiUrl: "https://api.example.com",
    timeout: 5000,
    retries: 3
};

// State management
let applicationState = {
    user: null,
    isLoading: false,
    error: null
};

// Counter patterns
let itemCount = 0;
const incrementCount = () => itemCount++;
const resetCount = () => itemCount = 0;

// Flag patterns
let hasPermission = false;
let isDataLoaded = false;
let shouldRefresh = true;

Variable Initialization Best Practices

Always initialize variables when possible to avoid undefined values:

javascript
// Preferred: Initialize with meaningful defaults
let userScore = 0;
let userName = "";
let userPreferences = {};
let taskList = [];

// Acceptable when null represents "no value"
let selectedItem = null;
let errorMessage = null;

// Avoid: Uninitialized variables
// let score; // undefined can cause issues

Understanding these variable concepts and patterns will provide a solid foundation for JavaScript development. Variables are used in every aspect of programming, from simple data storage to complex state management in applications. Master these fundamentals, and you'll write more reliable, maintainable JavaScript code.

Frequently Asked Questions

Q: What's the main difference between var, let, and const in JavaScript?

A: The key differences are scope and reassignment rules. var has function scope and can be redeclared, let has block scope and can be reassigned but not redeclared, and const has block scope and cannot be reassigned or redeclared after initialization. Modern JavaScript best practice is to use const by default and let when you need to reassign the variable.

Q: Can I use a variable before declaring it in JavaScript?

A: This depends on how you declare it. Variables declared with var are hoisted and return undefined when accessed before declaration. Variables declared with let and const are also hoisted but exist in a "temporal dead zone" and will throw a ReferenceError if accessed before declaration. Always declare variables before using them to avoid confusion.

Q: Why should I avoid using var in modern JavaScript?

A: The var keyword has several issues: it has function scope instead of block scope (which can cause unexpected behavior in loops and conditionals), it allows redeclaration in the same scope (which can mask bugs), and its hoisting behavior can be confusing. Using let and const provides better scoping rules, clearer intent, and helps prevent common programming errors.

Q: Can I change the contents of a const variable?

A: You cannot reassign a const variable, but if it contains an object or array, you can modify the contents. For example, const user = { name: "John" }; user.name = "Jane" is valid because you're modifying the object's property, not reassigning the variable itself. To make objects truly immutable, you need additional techniques like Object.freeze().

Q: What happens if I don't declare a variable with var, let, or const?

A: If you assign a value to an undeclared identifier, JavaScript creates a global variable automatically (in non-strict mode). This is called an "implicit global" and is considered bad practice because it can cause naming conflicts and make code harder to debug. Always use var, let, or const to explicitly declare variables, and consider using strict mode ("use strict") to prevent implicit globals.

Conclusion

Key Takeaways

  • JavaScript offers three variable declaration methods: var (function-scoped, hoisted), let (block-scoped, reassignable), and const (block-scoped, immutable reference)
  • Modern JavaScript best practice is to use const by default and let when reassignment is needed, avoiding var entirely
  • Understanding scope (global, function, and block) is crucial for preventing bugs and managing variable accessibility
  • Hoisting behavior differs between declaration methods, with let and const providing more predictable behavior than var
  • Proper naming conventions and initialization practices lead to more maintainable and readable code

Next Steps

  • Practice declaring variables with different methods to understand their scope behavior
  • Experiment with hoisting by trying to access variables before their declaration
  • Try building small projects using only let and const to get comfortable with modern variable declaration
  • Learn about data types and how they work with variables to deepen your JavaScript foundation
  • Explore advanced concepts like destructuring assignment and template literals that build upon variable knowledge
Tags:JavaScriptTutorial