Back to Home

Making Decisions

Have you ever wondered how applications make smart decisions? Like how a navigation system chooses the fastest route, or how a thermostat decides when to turn on the heat? This is the fundamental concept of decision-making in programming. Just as Charles Babbage’s Analytical Engine was designed to follow different sequences of operations based on conditions, modern JavaScript programs need to make choices based on varying circumstances. This ability to branch and make decisions is what transforms static code into responsive, intelligent applications. In this lesson, you’ll learn how to implement conditional logic in your programs. We’ll explore conditional statements, comparison operators, and logical expressions that allow your code to evaluate situations and respond appropriately.

Pre-Lecture Quiz

Pre-lecture quiz The ability to make decisions and control program flow is a fundamental aspect of programming. This section covers how to control the execution path of your JavaScript programs using Boolean values and conditional logic.

A Brief Recap on Booleans

Before exploring decision-making, let’s revisit Boolean values from our previous lesson. Named after mathematician George Boole, these values represent binary states – either true or false. There’s no ambiguity, no middle ground. These binary values form the foundation of all computational logic. Every decision your program makes ultimately reduces to a Boolean evaluation. Creating Boolean variables is straightforward: This creates two variables with explicit Boolean values. ✅ Booleans are named after the English mathematician, philosopher and logician George Boole (1815–1864).

Comparison Operators and Booleans

In practice, you’ll rarely set Boolean values manually. Instead, you’ll generate them by evaluating conditions: “Is this number greater than that one?” or “Are these values equal?” Comparison operators enable these evaluations. They compare values and return Boolean results based on the relationship between the operands. ✅ Check your knowledge by writing some comparisons in your browser’s console. Does any returned data surprise you?

🧠 Comparison Mastery Check: Understanding Boolean Logic

Test your comparison understanding: - Why do you think === (strict equality) is generally preferred over == (loose equality)? - Can you predict what 5 === ‘5’ returns? How about 5 == ‘5’? - What’s the difference between !== and !=?

If Statement

The if statement is like asking a question in your code. “If this condition is true, then do this thing.” It’s probably the most important tool you’ll use for making decisions in JavaScript. Here’s how it works: The condition goes inside the parentheses, and if it’s true, JavaScript runs the code inside the curly braces. If it’s false, JavaScript just skips that whole block. You’ll often use comparison operators to create these conditions. Let’s see a practical example: Since 1000 >= 800 evaluates to true, the code inside the block executes, displaying “Getting a new laptop!” in the console.

If..Else Statement

But what if you want your program to do something different when the condition is false? That’s where else comes in – it’s like having a backup plan. The else statement gives you a way to say “if this condition isn’t true, do this other thing instead.” Now since 500 >= 800 is false, JavaScript skips the first block and runs the else block instead. You’ll see “Can’t afford a new laptop, yet!” in the console. ✅ Test your understanding of this code and the following code by running it in a browser console. Change the values of the currentMoney and laptopPrice variables to change the returned console.log().

🎯 If-Else Logic Check: Branching Paths

Evaluate your conditional logic understanding: - What happens if currentMoney exactly equals laptopPrice? - Can you think of a real-world scenario where if-else logic would be useful? - How might you extend this to handle multiple price ranges?

Switch Statement

Sometimes you need to compare one value against multiple options. While you could chain several if..else statements, this approach becomes unwieldy. The switch statement provides a cleaner structure for handling multiple discrete values. The concept resembles the mechanical switching systems used in early telephone exchanges – one input value determines which specific path the execution follows. Here’s how it’s structured: - JavaScript evaluates the expression once - It looks through each case to find a match - When it finds a match, it runs that code block - The break tells JavaScript to stop and exit the switch - If no cases match, it runs the default block (if you have one) In this example, JavaScript sees that dayNumber is 2, finds the matching case 2, sets dayName to “Tuesday”, and then breaks out of the switch. The result? “Today is Tuesday” gets logged to the console. ✅ Test your understanding of this code and the following code by running it in a browser console. Change the values of the variable a to change the returned console.log().

🔄 Switch Statement Mastery: Multiple Options

Test your switch understanding: - What happens if you forget a break statement? - When would you use switch instead of multiple if-else statements? - Why is the default case useful even if you think you’ve covered all possibilities?

Logical Operators and Booleans

Complex decisions often require evaluating multiple conditions simultaneously. Just as Boolean algebra allows mathematicians to combine logical expressions, programming provides logical operators to connect multiple Boolean conditions. These operators enable sophisticated conditional logic by combining simple true/false evaluations. These operators let you combine conditions in useful ways: - AND (&&) means both conditions must be true - OR (||) means at least one condition must be true - NOT (!) flips true to false (and vice versa)

Conditions and Decisions with Logical Operators

Let’s see these logical operators in action with a more realistic example: In this example: we calculate a 20% discount price (640), then evaluate whether our available funds cover either the full price OR the discounted price. Since 600 meets the discounted price threshold of 640, the condition evaluates to true.

🧮 Logical Operators Check: Combining Conditions

Test your logical operator understanding: - In the expression A && B, what happens if A is false? Does B even get evaluated? - Can you think of a situation where you’d need all three operators (&&, ||, !) together? - What’s the difference between !user.isActive and user.isActive !== true?

Negation Operator

Sometimes it’s easier to think about when something is NOT true. Like instead of asking “Is the user logged in?”, you might want to ask “Is the user NOT logged in?” The exclamation mark (!) operator flips the logic for you. The ! operator is like saying “the opposite of…” – if something is true, ! makes it false, and vice versa.

Ternary Expressions

For simple conditional assignments, JavaScript provides the ternary operator. This concise syntax allows you to write a conditional expression in a single line, useful when you need to assign one of two values based on a condition. It reads like a question: “Is this condition true? If yes, use this value. If no, use that value.” Below is a more tangible example: ✅ Take a minute to read this code a few times. Do you understand how these operators are working? Here’s what this line is saying: “Is firstNumber greater than secondNumber? If yes, put firstNumber in biggestNumber. If no, put secondNumber in biggestNumber.” The ternary operator is just a shorter way to write this traditional if..else statement:

Both approaches produce identical results. The ternary operator offers conciseness, while the traditional if-else structure may be more readable for complex conditions.

🚀 Challenge

Create a program that is written first with logical operators, and then rewrite it using a ternary expression. What’s your preferred syntax?

GitHub Copilot Agent Challenge 🚀

Use the Agent mode to complete the following challenge: Description: Create a comprehensive grade calculator that demonstrates multiple decision-making concepts from this lesson, including if-else statements, switch statements, logical operators, and ternary expressions. Prompt: Write a JavaScript program that takes a student’s numerical score (0-100) and determines their letter grade using the following criteria: - A: 90-100 - B: 80-89 - C: 70-79 - D: 60-69 - F: Below 60 Requirements: 1. Use an if-else statement to determine the letter grade 2. Use logical operators to check if the student passes (grade >= 60) AND has honors (grade >= 90) 3. Use a switch statement to provide specific feedback for each letter grade 4. Use a ternary operator to determine if the student is eligible for the next course (grade >= 70) 5. Include input validation to ensure the score is between 0 and 100 Test your program with various scores including edge cases like 59, 60, 89, 90, and invalid inputs. Learn more about agent mode here.

Post-Lecture Quiz

Post-lecture quiz

Review & Self Study

Read more about the many operators available to the user on MDN. Go through Josh Comeau’s wonderful operator lookup!

Assignment

Operators

🧠 Your Decision-Making Toolkit Summary


🚀 Your JavaScript Decision-Making Mastery Timeline

⚡ What You Can Do in the Next 5 Minutes

journey
    title Your JavaScript Decision-Making Adventure
    section Foundation
      Boolean Values: 5: You
      Comparison Operators: 4: You
      Logical Thinking: 5: You
    section Basic Decisions
      If Statements: 4: You
      If-Else Logic: 5: You
      Switch Statements: 4: You
    section Advanced Logic
      Logical Operators: 5: You
      Complex Conditions: 4: You
      Ternary Expressions: 5: You
Example:

Follow the lesson from Microsoft Web-Dev-For-Beginners course

Tags: web,development