How JavaScript Executes Code — Functions & Callbacks Explained (JavaScript from Scratch Part 2)
Control Flow, Loops & Functions
In the previous article (Read my previous article) we covered Variables, Scope, Data Types, and Operators the core foundation of JavaScript.
In this article, we move forward to understand how JavaScript controls execution flow and how we reuse logic using functions.
Topics covered:
- Control Flow Statements (if, switch, ternary)
- Loops (for, while, forEach)
- Functions
These concepts are essential for writing real programs and application logic.
Control Flow Statements
Control flow determines how code executes step by step in a program.
Get Hasani Madhumali’s stories in your inbox
Join Medium for free to get updates from this writer.
Main types:
- Conditional Statements
- Loops
- Error Handling (
try...catch)
1. Conditional Statements
Used to execute different code based on conditions.
if, else if, else
let age = 18;
if (age < 18) {
console.log("Minor");
} else if (age === 18) {
console.log("Just Adult");
} else {
console.log("Adult");
}switch Statement
Used to execute code based on a value.
// syntax
switch (key) { // key can be a number, string, or expression.
case value1:
// code
break;
case value2:
// code
break;
default:
// default code
}
// Example
let day = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Other day");
}Ternary Operator
The conditional (ternary) operator is an expression that returns one of two values based on a condition.
It is often compared to a shorthand form of if...else, but unlike control flow statements, it returns a value and is mainly used inside expressions.
// syntax
condition ? "If True" : "If False";
// Example
let age = 20;
let result = age >= 18 ? "Adult" : "Minor";
console.log(result); // Adult2. Loops in JavaScript
Loops are used to execute a block of code repeatedly until a condition is met. They help automate repetitive tasks and reduce duplicate code.
for Loop
The for loop is commonly used when the number of iterations is known.
// Syntax
for (initialization; condition; increment/decrement) {
//code to execute
}
// Example
for (let i = 0; i < 3; i++) {
console.log(i);
}
// Output
0
1
2while Loop
The while loop runs as long as the condition is true. It is useful when the number of iterations is not known beforehand.
// Syntax
while (condition) {
//code to execute
update the loop counter;
}
// Example
let i = 0;
while (i < 3) {
console.log(i);
i++;
}
//Output
0
1
2do…while Loop
The do...while loop executes the code at least once, then checks the condition.
// Syntax
do {
//code to execute
update the loop counter;
} while (condition);
// Example
let i = 0;
do {
console.log(i);
i++;
} while (i < 3);
// Output
0
1
2forEach Loop (Array Loop)
Used to loop through arrays.
// Syntax
array.forEach(function(element, index, array) {
// code to execute for each element
});
element → current item in the array
index (optional) → position of the element
array (optional) → original array being looped
// Example
const numbers = [10, 20, 30];
numbers.forEach(function(num) {
console.log(num);
});Key Differences
for→ Best when iteration count is knownwhile→ Runs only if condition is truedo...while→ Runs at least once, even if condition is false
break and continue
break→ stops loop completelycontinue→ skips current iteration
for (let i = 0; i < 5; i++) {
if (i === 3) break; // stops loop
console.log(i);
}
for (let i = 0; i < 5; i++) {
if (i === 2) continue; // skips current iteration
console.log(i);
}for…of (Important — Modern Loop)
Used for arrays and iterable values.
let nums = [10, 20, 30];
for (let n of nums) {
console.log(n);
}for…in
Used for object keys.
let person = { name: "John", age: 25 };
for (let key in person) {
console.log(key, person[key]);
}3. Error Handling — try…catch
Used to handle runtime errors safely.
try {
let x = y; // error
} catch (error) {
console.log("Error handled:", error.message);
} finally {
console.log("Always runs");
}
// Example: handling JSON error
try {
JSON.parse("{invalid json}");
} catch (error) {
console.log("Invalid JSON:", error.message);
}Functions in JavaScript
Functions are reusable blocks of code.
Basic Function
function greet(name) {
console.log("Hello " + name);
}
greet("John");Function with Default Parameters
function sum(x, y = 10) {
return x + y;
}
console.log(sum(10)); // 20
console.log(sum(10, 20)); // 30Function Expression
const sum = function (a, b) {
return a + b;
};
console.log(sum(2, 3));Anonymous Function
Function without a name.
(function () {
console.log("Hello world");
})();Arrow Function (Modern)
const sum = (a, b) => a + b;
console.log(sum(5, 3));Callback Functions
A callback is a function passed as an argument to another function and executed later, usually after a task is completed.
function display(result) {
console.log(result);
}
function add(n1, n2, myCallback) {
let sum = n1 + n2;
myCallback(sum);
}
add(10, 20, display);
setTimeout (Async Callback)
Runs after a delay.
setTimeout(function () {
console.log("Runs after 2 seconds");
}, 2000);Recursive Function
A recursive function calls itself.
Must include a stopping condition to avoid infinite loop.
function count(num) {
if (num <= 0) return;
console.log(num);
count(num - 1);
}
count(5);These are heavily used in real-world programming, from simple scripts to complex applications.
If you notice anything that needs improvement, correction feel free to respond. Learning is a continuous journey, and refining fundamentals makes a strong JavaScript developer.
Next -> JavaScript Objects







