Today, I learned about functions in JavaScript — how they are declared, how they work, and some basic control flow using if, else, and else if blocks.
🔹What is a Function in JavaScript?
A function is a reusable block of code that performs a specific task. You can define a function using the function keyword followed by a name and a
function greet() {
console.log("Hello, world!");
}
You can call the function by using its name:
greet(); // Output: Hello, world!
🔹Dynamic Functions with Parameters
Functions can also accept parameters, which makes them dynamic and reusable with different inputs. For example, summing two numbers:
function sum(a, b) {
console.log("Sum is:", a + b);
}
sum(5, 3); // Output: Sum is: 8
Here, a and b are parameters, and we passed different values (arguments) when calling the function.
🔹Returning Values from Functions
You can also return a value from a function using the return keyword:
function multiply(x, y) {
return x * y;
}
let result = multiply(4, 5);
console.log(result); // Output: 20
🔹If / Else Conditions
I also learned about basic conditional logic using if, else, and else if:
let num = 10;
if (num > 10) {
console.log("Greater than 10");
} else if (num === 10) {
console.log("Equal to 10");
} else {
console.log("Less than 10");
}
These are used to control the flow based on conditions.
🔹for loop
— what it is and how it works.
A for loop is used to perform repetitive tasks. It runs a block of code multiple times based on a condition.
The for loop has three main parts:
Initialization– where we set the starting point (e.g., let i = 0)
Condition check – the loop runs only if this condition is true
_Increment/Update _– after each iteration, the loop variable is updated (e.g., i++)
If the condition becomes false, the loop stops.
Example:
for (let i = 0; i < 5; i++) {
console.log(i);
}
What happens here:
Initialization: let i = 0
Condition: i < 5 → if true, run the block
After printing i, increment i using i++
Repeat until i < 5 becomes false
📌 Summary
- A function performs a task and can be reused.
- You can pass parameters to make it dynamic.
- Functions can return values.
- Use if, else if, and else to control decision-making in code.
Until tomorrow, Happy coding
Top comments (0)