Activity: Store and display user name
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.
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?
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.
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.
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.
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!
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?
CodyMcTweak: Great question! Here are the best practices for JavaScript variables:
let or const - never leave them undeclaredconst by default, and only use let when you need to reassign the variableLet's rewrite this code together with these principles in mind.
AllyMcTweak: Let's start by giving our variables proper declarations and meaningful names. Here's a first pass:
// 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: 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!
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!
CodyMcTweak: Let's incorporate everyone's suggestions into a final, properly documented and structured 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: *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:
let declarationsThis makes the code not only work correctly but also be maintainable and understandable by other developers!
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.
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.
// Output will appear here after you run the code
Try modifying the code above to:
prompt()new Date().getHours()letUse for variables whose values will change
let score = 0;
score = 100; // Can be reassigned
constUse 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";
firstName, totalScore)if, for, function)score and Score are different variables)const by default, only use let when you need to reassignlet or const (never leave them undeclared)const for values that won't change and let for values that will
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!