JavaScript 101: Advanced Decisions and Mastering Text (Part 3)
Welcome back to the series! In Part 2, we gave our code a brain by teaching it to make simple if-else decisions and to be more efficient with functions. Now, it's time to upgrade that brain and give it a voice.
In this session, we'll explore more complex decision-making to handle multiple scenarios. Then, we'll take a deep dive into one of the most fundamental data types you'll ever work with: strings. From validating a user's password to crafting personalized messages, mastering text is a non-negotiable skill for any developer.
Ready to level up? Let's begin.
What You'll Learn in This Session:
How to handle multiple conditions with chains.
How to make decisions within decisions using nested .
How to access and manipulate individual characters in a string.
The crucial concept of String Immutability.
A modern, clean way to build strings with Template Literals.
How to use powerful built-in String Methods.
Level 2 Decisions: if-else if-else Chains
In our last session, we used if-else to handle two outcomes: A or B. But what if there are more options? C, D, E...?
The chain lets you test multiple, mutually exclusive conditions in a sequence. As soon as one condition is met, its code block runs, and the rest of the chain is skipped.
Adaptive Example: Assigning Student Grades Imagine a program that assigns a letter grade based on a score.
If the score is over 90, the grade is 'A'.
Otherwise, if the score is over 80, the grade is 'B'.
Otherwise, if the score is over 70, the grade is 'C'.
For anything else, the grade is 'F'.
const score = 85;
let grade;
if (score > 90) {
grade = 'A';
} elseif (score > 80) { // This only runs if the first 'if' was false
grade = 'B';
} elseif (score > 70) { // This only runs if the first two were false
grade = 'C';
} else {
grade = 'F';
}
console.log(`The student's grade is: ${grade}`); // Output: The student's grade is: B
Level 3 Decisions: Nested if-else
Sometimes, you need to check a condition only if another condition is already true. This is called a nested —an if inside another if.
Adaptive Example: Checking Blood Donation Eligibility To be eligible to donate blood, a person must meet several criteria. Let's say they must be 18 or older, AND they must weigh more than 50 kg.
First Check: Is the person old enough?
Second Check (nested):If they are old enough, is their weight sufficient?
const personAge = 25;
const personWeight = 60;
let eligibilityStatus;
// First, check the ageif (personAge >= 18) {
// If age is okay, THEN we check the weightif (personWeight > 50) {
eligibilityStatus = "Eligible";
} else {
eligibilityStatus = "Not Eligible (underweight)";
}
} else {
// If the first 'if' was false, we don't even need to check weight
eligibilityStatus = "Not Eligible (underage)";
}
console.log(eligibilityStatus); // Output: Eligible
A Deep Dive into Strings
From usernames and passwords to articles and chat messages, text (or strings) is everywhere on the web. Let's learn how to work with it effectively.
Accessing String Info: Length and Characters
Think of a string as a row of numbered boxes, with each box holding one character.
"JavaScript" | J | a | v | a | S | c | r | i | p | t | |---|---|---|---|---|---|---|---|---|---| | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
Key Points:
Indexing starts at 0! The first character is at index 0, the second at index 1, and so on. This is a fundamental concept in almost all programming languages.
Property: To find out how many characters are in a string, you can use .length.
const language = "JavaScript";
// Get the total number of charactersconsole.log(language.length); // Output: 10// Access a specific character using bracket notation []console.log(language[0]); // Output: 'J' (the first character)console.log(language[4]); // Output: 'S' (the fifth character)// What's the last character?// It will be at index (length - 1)const lastIndex = language.length - 1; // 10 - 1 = 9console.log(language[lastIndex]); // Output: 't'
This is extremely useful for validation, like checking if a password is long enough.
The Unchangeable Nature of Strings: Immutability
This is a concept that often trips up beginners. In JavaScript, strings are immutable, which means once a string is created, its individual characters cannot be changed.
Let's try to "fix" a typo:
let myName = "Tane"; // Oops, should be "Jane"
myName[0] = "J"; // Let's try to change the 'T' to a 'J'console.log(myName); // Output: "Tane"
It didn't work! The original string "Tane" was not altered.
So how do you "change" a string? You don't. You create a new string with the corrected value and reassign the variable to point to it.
let myName = "Tane";
myName = "Jane"; // This creates a brand new string and reassigns the variable.console.log(myName); // Output: "Jane"
This is why string methods (which we'll see next) don't change the original string; they always return a new, modified string.
The Modern Way to Build Strings: Template Literals
Remember joining strings with the + operator? It works, but it can get messy.
let name = "Alex";
let items = 3;
// The old way:let message = "Hello " + name + ", you have " + items + " items in your cart.";
Modern JavaScript gives us a much cleaner way: Template Literals (or Template Strings).
How to use them:
Use backticks ` instead of single or double quotes.
Embed variables or any JavaScript expression directly inside the string by wrapping them in ${...}.
let name = "Alex";
let items = 3;
// The modern way:let message = `Hello ${name}, you have ${items} items in your cart.`;
console.log(message); // Output: Hello Alex, you have 3 items in your cart.// You can even do math inside!let personalizedMessage = `Next year, you will have ${items + 1} items.`;
console.log(personalizedMessage); // Output: Next year, you will have 4 items.
Template literals also make multi-line strings incredibly simple—just press Enter!
Your Toolkit: String Methods and Reading Documentation
JavaScript comes with a rich set of built-in functions for strings, called methods. You don't need to memorize them all. The most important skill is knowing that they exist and how to look them up.
Adaptive Example: Processing a Username Let's say a user signs up with the email AnNa.Smith@Example.COM. We want to standardize it.
const userEmail = " AnNa.Smith@Example.COM ";
// 1. .trim(): Removes whitespace from both endslet trimmedEmail = userEmail.trim();
// trimmedEmail is now "AnNa.Smith@Example.COM"// 2. .toLowerCase(): Converts the entire string to lowercaselet lowerCaseEmail = trimmedEmail.toLowerCase();
// lowerCaseEmail is now "anna.smith@example.com"// 3. .substring(startIndex, endIndex): Extracts a part of the stringlet atIndex = lowerCaseEmail.indexOf('@'); // Find where the '@' is (index 10)let username = lowerCaseEmail.substring(0, atIndex);
// username is now "anna.smith"console.log(`The standardized username is: ${username}`);
// Output: The standardized username is: anna.smith
Notice how each method returned a new string, which we stored in a new variable. The original userEmail string remains unchanged due to immutability.
Conclusion & What's Next
You've made huge strides today! You can now write programs that handle complex, multi-layered logic and can confidently manipulate text data, a skill you'll use in every project.
Today, you mastered:
chains and nested for sophisticated decision-making.
The core properties of strings: .length, zero-based indexing, and immutability.
The clean and powerful syntax of Template Literals.
The power of String Methods and the essential skill of reading documentation.
We are on the verge of unlocking the full potential of programming. In our next session, we will learn how to make our programs perform repetitive tasks automatically using loops and how to manage lists of data using arrays. See you then.
JavaScript 101: Your First Step into the World of Code (Part 1) Welcome to the start of your programming journey! If you've ever wondered how websites go from being static pages to interactive, dynamic experiences, you're in the right place. The magic behind it all is a powerful language called JavaScript . This series is designed for absolute beginners. We'll start from scratch, and by the end of this first post, you'll not only understand what JavaScript is but also write your very first lines of code. Ready? Let's get our laptops ready and dive in! What You'll Learn in This Session: Why we need JavaScript and where it's used. How to write and see the output of your first program. The basic "ingredients" of code: Primitive Data Types. How to store information using Variables ( var , let , and const ). The do's and don'ts of naming your variables. Why Do We Even Need JavaScript? Imagine you're building a house. HTML (HyperText Marku...
JavaScript 101: Acing the Interview - The Ultimate Q&A Guide (Part 11) Welcome to the final, and perhaps most practical, session of our JavaScript 101 series. You've learned the syntax, mastered the concepts, and even built a final project. Now, it's time to learn how to articulate that knowledge. Acing a technical interview isn't just about knowing the right answer; it's about explaining it clearly, confidently, and with examples that demonstrate true understanding. This post is your personal interview prep guide. We will cover the most common and crucial junior developer interview questions that have been touched upon throughout this series. We'll break down not just what to say, but how to say it, using real-world analogies to make your answers memorable and impressive. Acing Your Answers: The Structure for Success For each question, a strong answer generally follows this structure: Direct Definition: Start with a clear, concise definition. Key Diffe...
JavaScript 101: Automating Tasks with Loops & Managing Data with Arrays (Part 4) Hello and welcome back! In our last session, we leveled up our program's intelligence with advanced decision-making and took a deep dive into manipulating text with strings. You've learned how to make your code smart. Now, it's time to make it powerful and efficient . Imagine you had to send a personalized email to 1,000 users or calculate the total price of 50 items in a shopping cart. Doing this one by one would be impossible. This is where we introduce two of the most fundamental concepts in all of programming: Loops for automating repetitive tasks, and Arrays for managing lists of data. When you combine loops and arrays, you unlock the ability to process huge amounts of information with just a few lines of code. Let's get started! What You'll Learn in This Session: How to stop repeating yourself using the loop . How to create and manage ordered lists ...
Comments
Post a Comment