JavaScript and TypeScript course Β· Module 1: JavaScript Basics
Variable Declaration (var, let, const)
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.
1// Declaring variable dinosaur using the var keyword
2var dinosaur = "T-Rex";
3
4// Declaring variable height using the let keyword
5let height = 5.6;
6
7// Declaring constant MAX_SPEED using the const keyword
8const 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.
1function monitorDinosaurs() {
2 var count = 5;
3
4 if (count > 3) {
5 var status = "Safety limit exceeded!";
6 console.log(status); // "Safety limit exceeded!"
7 }
8
9 console.log(status); // "Safety limit exceeded!" - variable is accessible outside the if block
10}
11
12// console.log(count); // Error! 'count' is not defined - var has function scopeIt'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.
1function securityCheck() {
2 let safetyStatus = "Normal";
3
4 if (emergencyDetected) {
5 let alarmLevel = "Red";
6 console.log(alarmLevel); // "Red"
7 }
8
9 // console.log(alarmLevel); // Error! 'alarmLevel' is not defined - variable accessible only in the if block
10}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.
1function setupEnclosure() {
2 const ENCLOSURE_ID = "A-7";
3 const MAX_CAPACITY = 3;
4
5 // ENCLOSURE_ID = "B-3"; // Error! Cannot change the value of a constant
6
7 let currentDinosaurs = 2;
8 currentDinosaurs = 3; // OK - let variables can change value
9}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:
1console.log(dinosaurCount); // undefined - the declaration is hoisted, but not the initialization
2var dinosaurCount = 10;This is equivalent to:
1var dinosaurCount; // Declaration is hoisted to the top
2console.log(dinosaurCount); // undefined
3dinosaurCount = 10; // Initialization remains in its original place2. 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:
1// console.log(dinoSpecies); // Error: Cannot access 'dinoSpecies' before initialization
2let dinoSpecies = "Velociraptor";
3
4// console.log(MAX_WEIGHT); // Error: Cannot access 'MAX_WEIGHT' before initialization
5const 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
1var securityLevel = "Low";
2var securityLevel = "High"; // Allowed - overwrites the previous declarationIt'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
1let carnivoreCount = 5;
2// let carnivoreCount = 7; // Error! 'carnivoreCount' has already been declared
3
4const MAX_VISITORS = 150;
5// const MAX_VISITORS = 200; // Error! 'MAX_VISITORS' has already been declaredIt'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:
1const PARK_NAME = "Jurassic Park";
2const ADMIN_PASSWORD = "clevergirl123";
3const DANGEROUS_SPECIES = ["T-Rex", "Velociraptor", "Dilophosaurus"];Even for objects and arrays whose contents may change, but the reference remains constant:
1const parkStatus = {
2 isOpen: true,
3 visitorCount: 372
4};
5
6// Allowed - we're changing a property of the object, not the reference itself
7parkStatus.visitorCount = 373;
8
9// Error! Cannot assign a new object to a constant
10// 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:
1function monitorParkSectors() {
2 for (let i = 0; i < sectors.length; i++) {
3 let currentSector = sectors[i];
4 let dangerLevel = assessDanger(currentSector);
5
6 if (dangerLevel > 7) {
7 let emergencyProtocol = selectProtocol(dangerLevel);
8 activateAlarm(currentSector, emergencyProtocol);
9 }
10 }
11 // Variables i, currentSector, dangerLevel, emergencyProtocol are no longer accessible here
12}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.
1function legacyCode() {
2 if (condition) {
3 var oldSystemVariable = "value";
4 }
5
6 // Accessing the variable outside the block where it was declared
7 console.log(oldSystemVariable);
8}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.
1// Start with const
2const dinoData = fetchDinosaurData();
3
4// If you need to modify the value, use let
5let dangerLevel = 0;
6for (const dino of dinoData) {
7 if (dino.aggressive) {
8 dangerLevel++;
9 }
10}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:
1function processEnclosure(enclosureId) {
2 // All declarations at the beginning
3 const enclosure = getEnclosure(enclosureId);
4 let dinosaurCount = enclosure.inhabitants.length;
5 let feedingRequired = false;
6
7 // Function logic below
8 if (timeElapsed > 4) {
9 feedingRequired = true;
10 }
11
12 //
13}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:
1// BAD
2const x = 5;
3let y = getZ();
4
5// GOOD
6const maxDinosaursPerEnclosure = 5;
7let 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:
1// Defining types for better safety
2let dinoName: string = "Velociraptor";
3const maxSpeed: number = 45;
4const isDangerous: boolean = true;
5
6// Defining complex types
7interface Dinosaur {
8 name: string;
9 species: string;
10 height: number;
11 weight: number;
12 dangerous: boolean;
13}
14
15const trex: Dinosaur = {
16 name: "Rexy",
17 species: "Tyrannosaurus Rex",
18 height: 5.6,
19 weight: 8000,
20 dangerous: true
21};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:
1// Constant configuration values - do not change
2const PARK_NAME = "Jurassic Park";
3const DANGER_LEVELS = {
4 LOW: 1,
5 MEDIUM: 2,
6 HIGH: 3,
7 CRITICAL: 4
8};
9const DANGEROUS_SPECIES = ["T-Rex", "Velociraptor", "Dilophosaurus"];
10
11// Park monitoring function
12function monitorPark() {
13 // Park state - can change
14 let isOpen = true;
15 let visitorCount = getCurrentVisitors();
16 let activeAlerts = [];
17
18 // Review each sector
19 for (let i = 0; i < parkSectors.length; i++) {
20 const sector = parkSectors[i]; // Reference to sector doesn't change in the loop
21 let sectorStatus = checkSectorStatus(sector);
22
23 // Check dinosaurs in the sector
24 for (const dinosaur of sector.dinosaurs) {
25 // Species is constant - doesn't change
26 const species = dinosaur.species;
27
28 // Danger level can change
29 let dangerLevel = DANGER_LEVELS.LOW;
30
31 // Threat assessment
32 if (DANGEROUS_SPECIES.includes(species)) {
33 dangerLevel = DANGER_LEVELS.HIGH;
34
35 // Check security infrastructure
36 const fenceStatus = checkFenceStatus(sector.id);
37 const powerStatus = checkPowerStatus(sector.id);
38
39 if (fenceStatus !== "Operational" || powerStatus < 90) {
40 dangerLevel = DANGER_LEVELS.CRITICAL;
41
42 // Local emergency protocol
43 let emergencyProtocol = selectEmergencyProtocol(species);
44 activeAlerts.push({
45 sector: sector.id,
46 species: species,
47 protocol: emergencyProtocol
48 });
49
50 // Adding an alert may affect park status
51 if (dangerLevel === DANGER_LEVELS.CRITICAL) {
52 isOpen = false;
53 }
54 }
55 }
56 }
57 }
58
59 // Return park status report
60 return {
61 parkName: PARK_NAME,
62 open: isOpen,
63 visitors: visitorCount,
64 alerts: activeAlerts
65 };
66}Summary
var:
- Has function scope
- Is fully hoisted
- Allows redeclaration
- Like older, less secure enclosures in the park
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
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
1// Park Patrol - Loops and Iteration
2// Exercise: Using for, while, for...of loops
3
4// for loop - classic iteration
5console.log("=== Enclosure Patrol (for loop) ===");
6const enclosures = ["T-Rex", "Raptor", "Triceratops", "Brachio", "Stego"];
7
8for (let i = 0; i < enclosures.length; i++) {
9 console.log("Enclosure " + (i + 1) + ": " + enclosures[i] + " - OK");
10}
11
12// for...of loop - iterating over elements
13console.log("\n=== Feeding (for...of) ===");
14for (const dino of enclosures) {
15 console.log("Feeding: " + dino);
16}
17
18// while loop
19console.log("\n=== DNA Scanning (while) ===");
20let samples = 3;
21while (samples > 0) {
22 console.log("Scanning sample " + samples + "...");
23 samples--;
24}
25
26// Your task:
27// 1. Use a for loop to search the DNA database
28// 2. Use for...of to list species
29// 3. Use while with a stopping condition
30
31// Your code here:
32Spotted 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. What is a variable in JavaScript?
2. Which variable declaration keyword prevents reassignment of a value?
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: