Copy
Strings, numbers, booleans - the building blocks of JavaScript
Activity: Type detection game
In this episode, the McTweak family will explore the fundamental data types in JavaScript: strings, numbers, and booleans. Understanding these building blocks is essential for writing effective and well-documented code.
Today's mission: Help a rookie coder understand and properly document JavaScript data types in their code.
CodyMcTweak: Hey team, we've got another rookie coder submission. The code technically works, but there are zero comments explaining the data types being used. Check this out...
let name = "Alex";
let age = 25;
let isStudent = true;
function displayUserInfo() {
let output = name + " is " + age + " years old. Student: " + isStudent;
return output;
}
function calculateBirthYear() {
let currentYear = 2024;
let birthYear = currentYear - age;
return birthYear;
}
function checkEligibility() {
if (age >= 18 && isStudent) {
return "Eligible for student discount";
} else if (age >= 18 && !isStudent) {
return "Eligible for adult pricing";
} else {
return "Eligible for child pricing";
}
}
console.log(displayUserInfo());
console.log("Birth year: " + calculateBirthYear());
console.log(checkEligibility());
AshleyMcTweak: It looks like the code works... what's the big deal about documenting data types? Can't you just tell what they are by looking at the values?
TrashyMcTweak: Oh sure, because everyone loves playing "Guess That Data Type" when they're maintaining code at 3 AM during a production emergency! This code is about as helpful as a chocolate teapot.
JavaScript is dynamically typed, which means it's even MORE important to document what types you're expecting. Without comments, this is just asking for bugs to move in and start paying rent.
AllyMcTweak: Ashley, let me explain. JavaScript has several primitive data types, but the three most common ones in this code are:
GarbageMcTweak: *sigh* Let me pause my high score attempt to explain why this matters. JavaScript doesn't force you to declare what type a variable is when you create it.
This is called dynamic typing, which means variables can change types during program execution. For example:
let x = "hello"; // x is a string
x = 42; // now x is a number
x = true; // now x is a boolean
This flexibility is both a blessing and a curse. It makes JavaScript easy to use but can lead to unexpected bugs if you're not careful.
GrumpyMcTweak: ANOTHER SECURITY NIGHTMARE! JavaScript also does automatic type conversion, called type coercion, which can lead to TERRIBLE, HORRIBLE BUGS!
For example, look at this mess:
"5" + 2 // Gives "52" (string concatenation)
"5" - 2 // Gives 3 (numeric subtraction)
"5" * "2" // Gives 10 (numeric multiplication)
THIS IS WHY WE NEED COMMENTS! The next developer needs to know what type you're EXPECTING, so they don't accidentally introduce bugs!
FattyMcTweak: Let me serve up a premium solution! We need to add clear comments that explain what types each variable should contain. This is like adding ingredient labels to a recipe - it helps the next chef know exactly what they're working with!
Here's how we can improve this code with proper type documentation:
/**
* User Information Variables
* These variables store basic information about the user
*/
// User's name (String)
let name = "Alex";
// User's age (Number)
let age = 25;
// Whether the user is a student (Boolean)
let isStudent = true;
/**
* Displays formatted user information
* @returns {String} Formatted string with user details
*/
function displayUserInfo() {
// Concatenate string and convert other types to string implicitly
let output = name + " is " + age + " years old. Student: " + isStudent;
return output;
}
/**
* Calculates the user's birth year based on current year and age
* @returns {Number} The calculated birth year
*/
function calculateBirthYear() {
// Current year (Number)
let currentYear = 2024;
// Calculate birth year (Number)
let birthYear = currentYear - age;
return birthYear;
}
/**
* Determines pricing eligibility based on age and student status
* @returns {String} The eligibility message
*/
function checkEligibility() {
// Check both age (Number) and student status (Boolean)
if (age >= 18 && isStudent) {
return "Eligible for student discount";
} else if (age >= 18 && !isStudent) {
return "Eligible for adult pricing";
} else {
return "Eligible for child pricing";
}
}
// Display all user information (outputs String)
console.log(displayUserInfo());
// Display birth year with label (outputs String)
console.log("Birth year: " + calculateBirthYear());
// Display eligibility status (outputs String)
console.log(checkEligibility());
CodyMcTweak: This is much better! Now anyone reading the code can immediately see what types each variable should contain. We've also added JSDoc comments to functions to indicate their return types.
The comments also explain any type conversions happening in the code, which helps prevent confusion about JavaScript's automatic type coercion.
AshleyMcTweak: Wow, I didn't realize how important documenting types was! So even though JavaScript doesn't force you to declare types like some other languages, we should still document them in comments?
TrashyMcTweak: Exactly! Just because JavaScript doesn't MAKE you declare types doesn't mean you should leave your fellow devs in the dark. That's like tossing someone into a maze blindfolded and saying "don't worry, there's probably an exit somewhere!"
Clear type documentation is the difference between code that's maintainable and code that makes the next developer contemplate a career change to goat herding.
SnowzieMcTweak: *woof woof*
(Translation: But how do we actually check what type a variable is in JavaScript?)
AllyMcTweak: Great question, Snowzie! JavaScript provides the typeof operator to check a variable's type. It returns a string indicating the data type:
typeof "Hello" // returns "string"
typeof 42 // returns "number"
typeof true // returns "boolean"
typeof undefined // returns "undefined"
typeof null // returns "object" (this is a known JavaScript quirk!)
typeof {} // returns "object"
typeof [] // returns "object" (arrays are objects in JavaScript)
typeof function() {} // returns "function"
GrumpyMcTweak: BEWARE OF EDGE CASES! The typeof operator isn't perfect! It says typeof null is "object" when null is its own primitive type! OUTRAGEOUS!
And arrays? typeof [] returns "object" too! If you need to check if something is an array, use Array.isArray([]) instead. Always be vigilant for JavaScript's TREACHEROUS quirks!
CodyMcTweak: Now that we understand the importance of data types and how to check them, let's practice with a type detection game! This will help you get comfortable identifying different data types in JavaScript.
GarbageMcTweak: *yawns* When you're done playing games, remember that in real-world code, using JSDoc comments to document expected types is even more helpful than just checking types at runtime.
Modern editors like VS Code will actually use those comments to give you hints and catch type errors before your code even runs. Less debugging means more time for gaming... I mean, "productive work activities."
typeof operator can be used to check a variable's type at runtime