Directing Your Code: Operators and Control Flow in JavaScript
Before this, we explored how JavaScript stores data using variables and the different types of data it can handle.
However, simply storing data isn’t enough. For a program to be meaningful, it must perform actions — like calculations, comparisons, and making decisions based on conditions. This is where Operators and Control Flow come into play.
In this article, we’ll explore the action elements of JavaScript (Operators) and the decision-making structure (Control Flow) that determine how your code executes.
1. Operators: The Verbs of Your Code
Operators are special symbols or keywords that perform actions on values (called operands). Whether you are doing math, comparing user inputs, or combining logic, operators make it happen.
Arithmetic Operators
Used for basic mathematical calculations.
+(Addition)-(Subtraction)*(Multiplication)/(Division)%(Modulus)**(Exponentiation/Power)
let a = 10, b = 3;
console.log(a + b); // 13
console.log(a % b); // 1 (Because 10 divided by 3 leaves a remainder of 1)
console.log(2 ** 3); // 8 (2 to the power of 3)Assignment Operators
Used to assign values to variables. They can also be combined with arithmetic operators for shorthand calculations.
=(Standard assignment)+=(Add and assign:a += bis the same asa = a + b)-=,*=,/=(Subtract, multiply, or divide and assign)
let score = 5;
score += 2; // score is now 7Comparison Operators
Used to compare two values. They always return a Boolean (true or false).
==(Loose equality - checks value only, auto-converts types)===(Strict equality - checks value AND type)!=(Loose not equal)!==(Strict not equal)>,<,>=,<=(Greater than, less than, etc.)
console.log(5 == "5"); // true (type conversion happens)
console.log(5 === "5"); // false (strict check fails because types differ)Logical Operators
Used to combine multiple conditions together. They rely heavily on the concepts of truthy and falsy values we discussed in Part 2.
&&(AND) - True only if both sides are true.||(OR) - True if at least one side is true.!(NOT) - Reverses the boolean value (true becomes false, false becomes true).
let age = 20;
let hasID = true;
if (age >= 18 && hasID) {
console.log("Entry Allowed"); // Both are true, so this runs
}Unary Operators
Operators that work on a single operand.
++(Increment by 1)--(Decrement by 1)+(Unary plus - a clever trick to instantly convert a string to a number!)typeof(Returns the data type)
let stringNum = "42";
let actualNum = +stringNum; // Converts "42" to the number 42
console.log(typeof actualNum); // "number"2. The Ternary Operator: Shorthand Decisions
Often, you need to assign a value based on a simple true/false condition. The Ternary Operator (? :) is a brilliant shorthand for a basic if/else statement.
Get Aman Verma’s stories in your inbox
Join Medium for free to get updates from this writer.
Syntax: condition ? valueIfTrue : valueIfFalse
Explanatory Code:
let age = 17;
// Using a standard if/else
let message;
if (age >= 18) {
message = "Adult";
} else {
message = "Minor";
}
// Using the Ternary Operator (Clean and simple!)
let quickMessage = age >= 18 ? "Adult" : "Minor";
console.log(quickMessage); // "Minor"Mindset Rule: Use the ternary operator for quick, single-line decisions. If your logic requires multiple steps or complex branches, stick to standard
if/elsestatements for better readability.
3. Control Flow: The Traffic Signals
If operators are the verbs, control flow is the traffic signal. It decides which blocks of code execute, when they execute, and what to skip entirely.
If / Else If / Else
The standard way to tell your program to make a decision. The code evaluates conditions from top to bottom. As soon as it finds a true condition, it executes that block and ignores the rest.
let marks = 78;
if (marks >= 90) {
console.log("Grade: A");
} else if (marks >= 75) {
console.log("Grade: B"); // This block runs!
} else {
console.log("Grade: C"); // This is the fallback
}Switch-Case
When you need to check a single variable against many possible exact values, switch is often cleaner than a massive chain of else if statements.
let weather = "rainy";
switch (weather) {
case "sunny":
console.log("Wear sunglasses.");
break; // Break prevents the code from running into the next case
case "rainy":
console.log("Take an umbrella."); // This runs
break;
case "snowy":
console.log("Wear a heavy coat.");
break;
default:
console.log("Check the forecast."); // Fallback if no cases match
}4. The Professional Touch: The Early Return Pattern
As you write more complex logic inside functions (which we will cover fully in Chapter 6), you might find yourself writing deeply nested if/else statements. This is often called "Callback Hell" or "Arrow Code" and makes your code incredibly hard to read.
Professionals use the Early Return Pattern to exit a function as soon as a condition fails, keeping the rest of the code clean and un-nested.
Bad (Deeply Nested):
function checkAge(age) {
if (age >= 18) {
// Lots of complex logic here...
return "Allowed";
} else {
return "Denied";
}
}Good (Early Return):
function checkAge(age) {
// 1. Handle the failure case immediately and exit
if (age < 18) return "Denied";
// 2. If the code reaches here, we know they are 18+
// Complex logic goes here without unnecessary indentation
return "Allowed";
}đź’ˇ Practice Zone
Test your logic gaps! Write code to solve the following challenges:
- Unary Conversion: How can you quickly convert the string
"100"to a number using a single unary operator? - Ternary Challenge: Write a one-line ternary statement that checks if a
scoreis greater than50. If it is, return"Pass", otherwise return"Fail". - Switch Logic: Create a
switchstatement that takes a string representing a day of the week (e.g.,"Monday") and prints whether it is a"Weekday"or"Weekend". - Predict the Output:
console.log("10" !== 10); console.log(true && false || true);







