JavaScript : Conditionals and Strings (Part 3)

 

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';
} else if (score > 80) { // This only runs if the first 'if' was false
  grade = 'B';
} else if (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.

  1. First Check: Is the person old enough?

  2. Second Check (nested): If they are old enough, is their weight sufficient?

const personAge = 25;
const personWeight = 60;
let eligibilityStatus;

// First, check the age
if (personAge >= 18) {
    // If age is okay, THEN we check the weight
    if (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:

  1. 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.

  2.  Property: To find out how many characters are in a string, you can use .length.

const language = "JavaScript";

// Get the total number of characters
console.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 = 9
console.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:

  1. Use backticks ` instead of single or double quotes.

  2. 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.

Your best friend for this is the Mozilla Developer Network (MDN) String documentation.

Here are a few common methods to get you started:

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 ends
let trimmedEmail = userEmail.trim();
// trimmedEmail is now "AnNa.Smith@Example.COM"

// 2. .toLowerCase(): Converts the entire string to lowercase
let lowerCaseEmail = trimmedEmail.toLowerCase();
// lowerCaseEmail is now "anna.smith@example.com"

// 3. .substring(startIndex, endIndex): Extracts a part of the string
let 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.

Comments

Popular posts from this blog

JavaScript: Data Types and Variables (Part 1)

JavaScript : Acing the Interview - The Ultimate Q&A Guide (Part 11)

JavaScript : Loops and Arrays (Part 4)