JavaScript and TypeScript course ยท Module 1: JavaScript Basics

Variable Declaration (var, let, const)

9 min read ยท
In this lesson7

In Jurassic Park, different dinosaur species require different security levels - the gentle Brachiosaurus can stay in an open range, while the aggressive Velociraptor needs a reinforced, enclosed facility. Similarly, in JavaScript we have three different ways to declare variables: var, let, and const, each offering a different level of "security" and flexibility.

Variable Declaration Basics

Variables in JavaScript are like labeled enclosures in Jurassic Park - they allow storing and organizing data that we can later reference. Before we can use a variable, we must declare it.

// Declaring variable dinosaur using the var keyword
var dinosaur = "T-Rex";

// Declaring variable height using the let keyword
let height = 5.6;

// Declaring constant MAX_SPEED using the const keyword
const MAX_SPEED = 27;

Differences Between var, let, and const

Variable Scope

1. var - Function Scope

Variables declared with var have function scope, meaning they are visible throughout the entire function in which they were declared.

function monitorDinosaurs() {
    var count = 5;

    if (count > 3) {
        var status = "Safety limit exceeded!";
        console.log(status);  // "Safety limit exceeded!"
    }

    console.log(status);  // "Safety limit exceeded!" - variable is accessible outside the if block
}

// console.log(count);  // Error! 'count' is not defined - var has function scope

It's like a security system where an alarm triggered in one part of the park (inside the if block) is still audible throughout the control center (function monitorDinosaurs), but not outside the park.

2. let - Block Scope

Variables declared with let have block scope - they are only visible within the block in which they were declared.

function securityCheck() {
    let safetyStatus = "Normal";

    if (emergencyDetected) {
        let alarmLevel = "Red";
        console.log(alarmLevel);  // "Red"
    }

    // console.log(alarmLevel);  // Error! 'alarmLevel' is not defined - variable accessible only in the if block
}

It's like radio communication with limited range - the alarm information (variable alarmLevel) is available only in the danger zone (the if block), not throughout the command center.

3. const - Immutable Value

const, like let, has block scope, but additionally introduces a restriction: once assigned, the value cannot be changed.

function setupEnclosure() {
    const ENCLOSURE_ID = "A-7";
    const MAX_CAPACITY = 3;

    // ENCLOSURE_ID = "B-3";  // Error! Cannot change the value of a constant

    let currentDinosaurs = 2;
    currentDinosaurs = 3;  // OK - let variables can change value
}

It's like enclosure identifiers in the park - once assigned, the enclosure number (e.g., "A-7") cannot be changed, to avoid mistakes and danger.

Hoisting

In JavaScript, variable and function declarations are "hoisted" to the top of their scope. It's like preparing all enclosures in the park before bringing in the dinosaurs.

1. var - Full Hoisting

Variables declared with var are hoisted along with their declaration, but without initialization:

console.log(dinosaurCount);  // undefined - the declaration is hoisted, but not the initialization
var dinosaurCount = 10;

This is equivalent to:

var dinosaurCount;  // Declaration is hoisted to the top
console.log(dinosaurCount);  // undefined
dinosaurCount = 10;  // Initialization remains in its original place

2. let and const - Partial Hoisting

Variables declared with let and const are also hoisted, but are not initialized - attempting to access them before declaration causes an error:

// console.log(dinoSpecies);  // Error: Cannot access 'dinoSpecies' before initialization
let dinoSpecies = "Velociraptor";

// console.log(MAX_WEIGHT);   // Error: Cannot access 'MAX_WEIGHT' before initialization
const MAX_WEIGHT = 8000;

It's like the securing procedure - enclosures are prepared (hoisting), but no one can enter them (use the variable) until they are officially opened (declared).

Redeclaration

1. var - Allows Redeclaration

var securityLevel = "Low";
var securityLevel = "High";  // Allowed - overwrites the previous declaration

It's like moving a dinosaur from one enclosure to another without any restrictions.

2. let and const - Do Not Allow Redeclaration in the Same Scope

let carnivoreCount = 5;
// let carnivoreCount = 7;  // Error! 'carnivoreCount' has already been declared

const MAX_VISITORS = 150;
// const MAX_VISITORS = 200;  // Error! 'MAX_VISITORS' has already been declared

It's like strict dinosaur relocation control - you cannot assign the same species to two different enclosures simultaneously.

When to Use var, let, and const

When to Use const

const is the safest option - use it whenever the variable's value will not change. It's like metal fences for predators:

const PARK_NAME = "Jurassic Park";
const ADMIN_PASSWORD = "clevergirl123";
const DANGEROUS_SPECIES = ["T-Rex", "Velociraptor", "Dilophosaurus"];

Even for objects and arrays whose contents may change, but the reference remains constant:

const parkStatus = {
    isOpen: true,
    visitorCount: 372
};

// Allowed - we're changing a property of the object, not the reference itself
parkStatus.visitorCount = 373;

// Error! Cannot assign a new object to a constant
// parkStatus = { isOpen: false, visitorCount: 0 };

When to Use let

let is a good choice for variables whose value will change, but we want to limit their scope to the current block. It's like flexible enclosures for gentler dinosaurs:

function monitorParkSectors() {
    for (let i = 0; i < sectors.length; i++) {
        let currentSector = sectors[i];
        let dangerLevel = assessDanger(currentSector);

        if (dangerLevel > 7) {
            let emergencyProtocol = selectProtocol(dangerLevel);
            activateAlarm(currentSector, emergencyProtocol);
        }
    }
    // Variables i, currentSector, dangerLevel, emergencyProtocol are no longer accessible here
}

When to Use var

Due to potential issues, var is currently rarely recommended in modern JavaScript. However, it can be useful in specific situations where we need a variable with function scope.

function legacyCode() {
    if (condition) {
        var oldSystemVariable = "value";
    }

    // Accessing the variable outside the block where it was declared
    console.log(oldSystemVariable);
}

It's like old, less secure enclosures in the park - they work, but it's better to replace them with more modern solutions.

Best Practices

1. Use const First

Always start with const for your variables. If you later find that you need to change the value, switch to let. It's like a rule in Jurassic Park - first apply the strongest security measures, and only if you need more flexibility, consider less restrictive options.

// Start with const
const dinoData = fetchDinosaurData();

// If you need to modify the value, use let
let dangerLevel = 0;
for (const dino of dinoData) {
    if (dino.aggressive) {
        dangerLevel++;
    }
}

2. Avoid var in New Code

In modern JavaScript (ES6+), it's generally better to use let and const instead of var.

3. Declare Variables at the Beginning of Their Scope

This helps understand which variables are used in a given code block:

function processEnclosure(enclosureId) {
    // All declarations at the beginning
    const enclosure = getEnclosure(enclosureId);
    let dinosaurCount = enclosure.inhabitants.length;
    let feedingRequired = false;

    // Function logic below
    if (timeElapsed > 4) {
        feedingRequired = true;
    }

    //
}

4. Use Meaningful Variable Names

Just as in the park, where every room or procedure has a clear label, in code variables should have meaningful names:

// BAD
const x = 5;
let y = getZ();

// GOOD
const maxDinosaursPerEnclosure = 5;
let currentSafetyRating = calculateSafetyScore();

Variable Declarations in TypeScript

TypeScript extends JavaScript with static typing, which provides an additional layer of security - like even sturdier fences in the park:

// Defining types for better safety
let dinoName: string = "Velociraptor";
const maxSpeed: number = 45;
const isDangerous: boolean = true;

// Defining complex types
interface Dinosaur {
    name: string;
    species: string;
    height: number;
    weight: number;
    dangerous: boolean;
}

const trex: Dinosaur = {
    name: "Rexy",
    species: "Tyrannosaurus Rex",
    height: 5.6,
    weight: 8000,
    dangerous: true
};

Types in TypeScript work like additional safety protocols - they prevent placing a "herbivore in a carnivore enclosure" (assigning a value of the wrong type).

Practical Example: Jurassic Park Monitoring System

The following example illustrates the proper use of var, let, and const in a more elaborate scenario:

// Constant configuration values - do not change
const PARK_NAME = "Jurassic Park";
const DANGER_LEVELS = {
    LOW: 1,
    MEDIUM: 2,
    HIGH: 3,
    CRITICAL: 4
};
const DANGEROUS_SPECIES = ["T-Rex", "Velociraptor", "Dilophosaurus"];

// Park monitoring function
function monitorPark() {
    // Park state - can change
    let isOpen = true;
    let visitorCount = getCurrentVisitors();
    let activeAlerts = [];

    // Review each sector
    for (let i = 0; i < parkSectors.length; i++) {
        const sector = parkSectors[i];  // Reference to sector doesn't change in the loop
        let sectorStatus = checkSectorStatus(sector);

        // Check dinosaurs in the sector
        for (const dinosaur of sector.dinosaurs) {
            // Species is constant - doesn't change
            const species = dinosaur.species;

            // Danger level can change
            let dangerLevel = DANGER_LEVELS.LOW;

            // Threat assessment
            if (DANGEROUS_SPECIES.includes(species)) {
                dangerLevel = DANGER_LEVELS.HIGH;

                // Check security infrastructure
                const fenceStatus = checkFenceStatus(sector.id);
                const powerStatus = checkPowerStatus(sector.id);

                if (fenceStatus !== "Operational" || powerStatus < 90) {
                    dangerLevel = DANGER_LEVELS.CRITICAL;

                    // Local emergency protocol
                    let emergencyProtocol = selectEmergencyProtocol(species);
                    activeAlerts.push({
                        sector: sector.id,
                        species: species,
                        protocol: emergencyProtocol
                    });

                    // Adding an alert may affect park status
                    if (dangerLevel === DANGER_LEVELS.CRITICAL) {
                        isOpen = false;
                    }
                }
            }
        }
    }

    // Return park status report
    return {
        parkName: PARK_NAME,
        open: isOpen,
        visitors: visitorCount,
        alerts: activeAlerts
    };
}

Summary

  1. var:

    • Has function scope
    • Is fully hoisted
    • Allows redeclaration
    • Like older, less secure enclosures in the park
  2. let:

    • Has block scope
    • Is partially hoisted (cannot be used before declaration)
    • Does not allow redeclaration in the same scope
    • Like standard enclosures with the ability to modify
  3. const:

    • Has block scope
    • Is partially hoisted (cannot be used before declaration)
    • Does not allow redeclaration or value reassignment
    • Allows modification of object and array contents
    • Like reinforced enclosures for the most dangerous dinosaurs

The choice between var, let, and const is like choosing the appropriate security measures in Jurassic Park - it depends on specific needs, but it's always worth starting with the strongest (const) and relaxing them only when absolutely necessary.

In the next lesson, we will look at basic data types in JavaScript, which are like different dinosaur species in our park - each with its own unique characteristics and applications.

Code for this lesson: index.js
// Park Patrol - Loops and Iteration
// Exercise: Using for, while, for...of loops

// for loop - classic iteration
console.log("=== Enclosure Patrol (for loop) ===");
const enclosures = ["T-Rex", "Raptor", "Triceratops", "Brachio", "Stego"];

for (let i = 0; i < enclosures.length; i++) {
  console.log("Enclosure " + (i + 1) + ": " + enclosures[i] + " - OK");
}

// for...of loop - iterating over elements
console.log("\n=== Feeding (for...of) ===");
for (const dino of enclosures) {
  console.log("Feeding: " + dino);
}

// while loop
console.log("\n=== DNA Scanning (while) ===");
let samples = 3;
while (samples > 0) {
  console.log("Scanning sample " + samples + "...");
  samples--;
}

// Your task:
// 1. Use a for loop to search the DNA database
// 2. Use for...of to list species
// 3. Use while with a stopping condition

// Your code here:

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What is a variable in JavaScript?

  2. 2. Which variable declaration keyword prevents reassignment of a value?

  3. 3. Does JavaScript distinguish between uppercase and lowercase letters?

Hands-on tasks in the game

  • Code editor

    Create variables: const labName = 'InGen', let dinoSpecies = 'Velociraptor', let population = 8. Display all of them in the console using console.log().

  • Click in order

    Arrange the constant declaration elements in the correct order:

  • Horizontal ordering

    Arrange the variable declaration elements with assignment:

  • Code editor

    Create a variable species and store a dinosaur species name in it as text, e.g. 'Tyrannosaurus Rex'.

  • Vertical ordering

    Arrange the stages of working with variables in JavaScript:

  • Click in order

    Arrange the elements of a let variable declaration:

  1. QuestionVariables in JavaScript
  2. QuestionVariables in JavaScript - const
  3. QuestionCase Sensitivity in JavaScript
  4. Coding taskPractice: Your First Variable
  5. Click in orderSorting: const Variable Declaration
  6. Put in orderVariable Declaration Syntax
  7. Coding taskExercise: Create a Variable Storing a Dinosaur Species
  8. Put in orderStages of Working with Variables
  9. Click in orderSorting: let Variable Declaration

Useful articles