Week 4 Day 1
New Terms
- Control Flow
- Conditional Statements
- Loops
- Logical Operators
- Assignment Operators
- Closure
- Scope
Control Flow
Control flow refers to the order in which a program’s statements are executed. JavaScript, like most programming languages, follows a top-to-bottom execution model—but we can manipulate this flow using conditional statements, loops, and function calls. By controlling the logic of execution, we can build dynamic, responsive applications.
Conditional Statements
Conditional statements allow JavaScript to make decisions based on certain conditions. The most common types include:
- if...else statements - Executes a block of code only if a condition is met.
- switch statements - Efficiently handles multiple conditions, often used when comparing a single variable against different values.
- Ternary Operator (condition ? trueValue : falseValue) - A shorthand way of writing simple conditional statements.
Loops
Loops are a fundamental programming feature that allows us to repeat a block of code multiple times. JavaScript offers several types of loops:
- for loop – Best for when the number of iterations is known.
- while loop – Runs as long as a specified condition is true.
- do...while loop – Similar to a while loop but guarantees at least one execution.
- forEach method – Specifically for iterating over arrays in a cleaner, more readable way.
Logical Operators
Logical operators allow us to combine and manipulate boolean values (true or false). The three main logical operators in JavaScript are:
- AND (&&) – Returns true only if both conditions are true.
- OR (||) – Returns true if at least one condition is true.
- NOT (!) – Reverses the boolean value of an expression.
Assignment Operators
Assignment operators allow us to assign values to variables in different ways. The most common is the = operator, but JavaScript provides several shorthand assignments:
- += – Adds and assigns (x += 5 is the same as x = x + 5).
- -= – Subtracts and assigns (x -= 3 is the same as x = x - 3).
- *=, /=, %= – Similar operations for multiplication, division, and remainder.
Closure
A closure is a function that retains access to its outer scope, even after the outer function has finished executing. This is a key concept in JavaScript that enables:
- Data encapsulation – Prevents variables from being accessed directly outside the function.
- State persistence – Useful for creating counters, event handlers, and private variables.
Scope
Scope determines where variables can be accessed in your code. JavaScript has three types of scope:
- Global Scope – Variables declared outside functions can be accessed anywhere.
- Function Scope – Variables declared inside a function are only accessible within that function.
- Block Scope (with let and const) – Variables inside {} are only accessible within that block.