Chapter 5, Episode 2

Variables: Storing Data in JavaScript

Chapter 5: JavaScript Basics – Making Websites Interactive! ✨ Lesson: let vs const declaration

Activity: Store and display user name

Previous Lesson Home Next Lesson

Variables: The Digital Storage Units of JavaScript

In this episode, the McTweak family will help a rookie coder understand JavaScript variables, the building blocks for storing and managing data in your code.

Today's mission: Review and improve a working but poorly commented piece of code that uses variables incorrectly and lacks proper documentation.

Scene 1: The Uncommented Variable Nightmare

CodyMcTweak

CodyMcTweak: Team, we've got an urgent situation. A junior dev just submitted this JavaScript code. It technically works, but look at those variables... no comments, confusing names, and mixing let and const without any apparent logic.

Can we please help them understand how to properly declare and document variables?

userGreeting.js (Original)
a = "John";
let stuff = "Doe";
const x = 25;
let y;

y = "Hello, " + a + " " + stuff + "! You are " + x + " years old.";

alert(y);

a = "Jane";
stuff = "Smith";
// x = 30; // Will cause an error because x is constant

let z = "Hello, " + a + " " + stuff + "! You are " + x + " years old.";

console.log(z);

TrashyMcTweak: *Dramatic gasp* What in the silicon-fried circuit board is THIS unholy mess?! Are those variable names or did someone just fall asleep on their keyboard?

Single-letter variables?! a, y, z? And what the heck is stuff supposed to mean? This isn't coding, it's cryptography! Even SkyNet would crash trying to maintain this garbage fire.

TrashyMcTweak
AshleyMcTweak

AshleyMcTweak: I'm still learning JavaScript... can someone first explain what variables actually are and why we need them? And what's the difference between let and const?

I see the code works, but I'm not sure why some variable declarations have keywords and that first one doesn't.

Scene 2: Variables 101

AllyMcTweak: Great question, Ashley! Variables are like labeled containers that store data in your program. They give us a way to save information so we can use it later.

Think of variables like digital sticky notes. You write a value on the note, give it a name, and then you can refer to that value by using the name instead of writing out the value again and again.

AllyMcTweak
FattyMcTweak

FattyMcTweak: And in modern JavaScript, we have a premium 3-course menu of ways to declare variables:

  • var - The old-school way (like that restaurant that's been around forever but nobody goes there anymore)
  • let - For variables whose values might change (like my meal choices throughout the day)
  • const - For variables that should never change (like my love for triple-decker sandwiches)

That first variable a has no declaration keyword, which is a major coding no-no. It's like serving a burger without telling anyone what kind of meat is in it!

GrumpyMcTweak: UNDECLARED VARIABLES ARE EXTREMELY DANGEROUS! They become global by default, polluting the global namespace faster than humans pollute their oceans!

And don't even get me started on those SINGLE-LETTER VARIABLE NAMES! What are we trying to conserve here, KEYSTROKES? Is the developer being charged PER CHARACTER?! Variables should be SELF-DOCUMENTING with CLEAR, DESCRIPTIVE names!

GrumpyMcTweak
GarbageMcTweak

GarbageMcTweak: *sighs* Let me put down my game controller for a minute to explain this... The difference between let and const is simple:

  • let - Use when your variable's value might change. Like my interest level in this conversation.
  • const - Use when your variable should NEVER change. Like my disappointment in humanity.

If you try to reassign a const variable, JavaScript throws an error. That commented-out line in the code would crash if it ran.

AshleyMcTweak: That makes sense! So what would be the best way to rewrite this code with proper variables and comments? And when should I use let versus const in my own code?

AshleyMcTweak
CodyMcTweak

CodyMcTweak: Great question! Here are the best practices for JavaScript variables:

  1. Always declare variables with let or const - never leave them undeclared
  2. Use const by default, and only use let when you need to reassign the variable
  3. Use descriptive, meaningful variable names (camelCase is the convention in JavaScript)
  4. Comment your variables to explain what they're for, especially if their purpose isn't immediately obvious

Let's rewrite this code together with these principles in mind.

Scene 3: First Round of Improvements

AllyMcTweak: Let's start by giving our variables proper declarations and meaningful names. Here's a first pass:

AllyMcTweak
userGreeting.js (First Improvement)
// Store user's first name
let firstName = "John";

// Store user's last name
let lastName = "Doe";

// Store user's age (constant since it doesn't change in this session)
const userAge = 25;

// Variable to store the greeting message
let greetingMessage;

greetingMessage = "Hello, " + firstName + " " + lastName + "! You are " + userAge + " years old.";

alert(greetingMessage);

firstName = "Jane";
lastName = "Smith";
// userAge = 30; // Will cause an error because userAge is constant

let updatedGreeting = "Hello, " + firstName + " " + lastName + "! You are " + userAge + " years old.";

console.log(updatedGreeting);
TrashyMcTweak

TrashyMcTweak: Well, it's marginally less terrible now. Like upgrading from "complete disaster" to just "major disappointment." At least the variable names make some sort of sense.

But we're still repeating that entire string concatenation mess twice! And those comments are about as useful as a chocolate teapot. "Store user's first name"? NO KIDDING! I thought firstName stored their shoe size!

GrumpyMcTweak: THE COMMENTS NEED MORE CONTEXT! WHY are we collecting this information? HOW is it being used? Also, WE COULD USE TEMPLATE LITERALS instead of that archaic string concatenation garbage!

AND FOR THE LOVE OF ALL THAT IS BINARY, CREATE A FUNCTION FOR THAT REPEATED GREETING LOGIC!

GrumpyMcTweak
FattyMcTweak

FattyMcTweak: Ooh, template literals! Yes, they're the premium deluxe option for string formatting - much cleaner and more flavorful than standard concatenation. Let me show you:

greetingMessage = `Hello, ${firstName} ${lastName}! You are ${userAge} years old.`

See those backticks and ${} placeholders? That's gourmet string interpolation right there!

Scene 4: The Final Polished Version

CodyMcTweak: Let's incorporate everyone's suggestions into a final, properly documented and structured version:

CodyMcTweak
userGreeting.js (Final Version)
/**
 * userGreeting.js
 * 
 * This script demonstrates the use of variables to store user data
 * and construct personalized greeting messages.
 */

// User information - firstName and lastName use let since they will change
let firstName = "John";
let lastName = "Doe";

// User's age - using const since this value doesn't change in our application
const userAge = 25;

/**
 * Creates a greeting message using the provided user information
 * 
 * @param {string} first - User's first name
 * @param {string} last - User's last name
 * @param {number} age - User's age
 * @returns {string} - Formatted greeting message
 */
function createGreeting(first, last, age) {
    return `Hello, ${first} ${last}! You are ${age} years old.`;
}

// Create and display the initial greeting
const initialGreeting = createGreeting(firstName, lastName, userAge);
alert(initialGreeting);

// Update the user information for a second example
firstName = "Jane";
lastName = "Smith";
// userAge = 30; // This would cause an error because userAge is a constant

// Create and log the updated greeting with the new information
const updatedGreeting = createGreeting(firstName, lastName, userAge);
console.log(updatedGreeting);
GarbageMcTweak

GarbageMcTweak: *reluctant nod* That's actually... not terrible. The function eliminates repetition, the comments explain both WHAT and WHY, and we've got proper JSDoc notation for that function.

Using let for variables that change and const for those that don't. And those template literals are much cleaner than concatenation. I can now return to my game with slightly less contempt for humanity.

AllyMcTweak: Let's highlight what we've improved:

  1. Replaced undeclared variable with proper let declarations
  2. Used descriptive variable names instead of single letters
  3. Added meaningful comments explaining the purpose of variables
  4. Created a function to eliminate repeated code
  5. Used template literals for cleaner string formatting
  6. Added JSDoc comments for better code documentation

This makes the code not only work correctly but also be maintainable and understandable by other developers!

AllyMcTweak
AshleyMcTweak

AshleyMcTweak: This is super helpful! I have one last question - what about var? Should I ever use that instead of let or const?

GrumpyMcTweak: NO! NEVER USE VAR! IT'S A RELIC OF DARKER TIMES!

CodyMcTweak: What Grumpy means is that var has function scope instead of block scope, which can lead to unexpected behaviors.

GarbageMcTweak: var is the programming equivalent of using a rotary phone. It works, but why would you when better options exist?

TrashyMcTweak: Using var in 2024 is like showing up to a cyberpunk party wearing a potato sack. Just don't.

GrumpyMcTweak CodyMcTweak
GarbageMcTweak TrashyMcTweak

Activity: Store and Display User Name

Now it's your turn to practice using variables! Let's create a simple script that stores a user's name and displays it in a greeting message.

Try it yourself:

// Output will appear here after you run the code

Challenge:

Try modifying the code above to:

  1. Ask for the user's first and last name using prompt()
  2. Store the current hour using new Date().getHours()
  3. Change the greeting based on the time of day (morning/afternoon/evening)
  4. Add proper comments explaining your variables and logic

JavaScript Variables: Quick Reference

Declaration Keywords:

let

Use for variables whose values will change

let score = 0;
score = 100; // Can be reassigned
const

Use for variables whose values will not change

const PI = 3.14159;
// PI = 3; // Error: cannot reassign
var (avoid using)

Older way to declare variables with function scope

// Not recommended in modern JS
var old = "legacy";

Variable Naming Conventions:

  • Use camelCase for variable names (e.g., firstName, totalScore)
  • Names should be descriptive and indicate purpose
  • Can contain letters, numbers, $ and _ (but cannot start with a number)
  • Cannot use reserved keywords (like if, for, function)
  • Case-sensitive (score and Score are different variables)

Best Practices:

  • Use const by default, only use let when you need to reassign
  • Declare variables at the top of their scope
  • Initialize variables when declaring them
  • Use descriptive comments to explain the purpose of variables
  • Avoid global variables when possible
  • Group related variables together

Episode Summary: What We Learned

SnowzieMcTweak

SnowzieMcTweak: *happy cyber-bark* Variables are like storing treats for later! You put them somewhere safe with a name you'll remember, and then you can fetch them whenever you need them!

Previous Lesson Home Next Lesson