Declaring and Calling Functions
Functions are blocks of code that perform a specific action. They are fundamental in JavaScript and help you write code that is more organized, reusable, and easier to maintain. A function can be defined once and called whenever you need it.
How to declare a function
A function is declared using the function keyword, followed by a name, parentheses, and curly
braces:
function greet() {
console.log("Hello, John!");
}
- function — the keyword that defines the function
- greet — the function name (can be any valid name)
- () — parentheses for any parameters
- {} — the code block that runs when the function is called
How to call a function
After defining the function, you can call it by writing its name followed by parentheses:
greet(); // Call the function
The result will appear in the console: Hello, John!
Live Example: Calling a function
Why functions are useful
Functions are essential for:
- Code reuse — write once, use multiple times
- Modularity — divide the application into logical components
- Clarity — code becomes easier to read and maintain
Helpful tips
- Choose descriptive names for functions:
calculateTotal(),displayMessage() - Don't forget to call them! A defined but uncalled function does nothing.
- You can define functions anywhere in the code, but it's good to keep them organized.
Function Parameters and Return Values
Functions can receive information from the outside through parameters and can send back a
result using return. This makes them much more flexible and useful in real applications.
Example with parameters
function greetName(name) {
console.log("Hello, " + name + "!");
}
greetName("John"); // Hello, John!
Example with return
function add(a, b) {
return a + b;
}
let result = add(5, 3);
console.log(result); // 8
Live Example: Adding with parameters
Key points
- You can have as many parameters as you want, separated by commas
returnstops the function execution and sends a value back- Functions without
returnreturn nothing (undefined)
Function Expressions vs Function Declarations
In JavaScript, you can define functions in two main ways: declarations and expressions. Although they look similar, there are important differences, especially regarding hoisting (lifting in memory).
Function Declaration
This is the classic form, which we have used so far:
function greet() {
console.log("Hello, John!");
}
greet(); // Works even if called before the definition
Function Expression
The function is stored in a variable:
const greet = function() {
console.log("Hello, John!");
};
greet(); // Works only after it has been defined
Live Example: Expression vs Declaration
Key Differences
- Declarations are hoisted — they can be called before being defined
- Expressions are not hoisted — they must be defined before calling
- Expressions can be anonymous, stored in variables, passed as arguments, etc.
Arrow Functions
Arrow functions are a shorter way to write functions in JavaScript. They are especially useful when you want
concise and quick code. They behave differently from classic functions regarding this, but for most
simple cases, they are perfect.
Basic Syntax
// Classic function
function greet(name) {
return "Hello, " + name + "!";
}
// Arrow function
const greet = (name) => {
return "Hello, " + name + "!";
};
Short Version
If the function has a single parameter and returns a value directly, you can write it even shorter:
const greet = name => "Hello, " + name + "!";
Live Example: Arrow Function
Differences Compared to Classic Functions
- They do not have their own
this— they use the outer context - Cannot be used as methods in objects if you need
this - Cannot be called with
new— they are not constructor functions
Iteration with for, while, and do...while
Loops are used to repeat an action multiple times. In JavaScript, the most common types of loops are
for, while, and do...while. Each has its own way to control execution.
for Loops
Ideal when you know exactly how many times you want to repeat something.
for (let i = 0; i < 5; i++) {
console.log("Step " + i);
}
while Loops
Executes the code as long as the condition is true.
let i = 0;
while (i < 5) {
console.log("Step " + i);
i++;
}
do...while Loops
Executes the code at least once, then checks the condition.
let i = 0;
do {
console.log("Step " + i);
i++;
} while (i < 5);
Example: Generate Steps with a for Loop
document.getElementById("generate").addEventListener("click", function () {
const list = document.getElementById("list");
list.innerHTML = "";
for (let i = 0; i < 5; i++) {
const item = document.createElement("li");
item.textContent = "Step " + i;
list.appendChild(item);
}
});
Key Takeaways
foris ideal for a fixed number of repetitionswhileis good when you don't know how many repetitions will occurdo...whileguarantees at least one execution
Iteration through Arrays and Strings
In JavaScript, you can iterate over the elements of an array or the characters of a string using loops. The
most common methods are for, for...of, and forEach for arrays, while for
strings you can use for or for...of.
Iterating an array with for
let fruits = ["apple", "pear", "plum"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Iterating an array with for...of
for (let fruit of fruits) {
console.log(fruit);
}
Iterating an array with forEach
fruits.forEach(function(fruit) {
console.log(fruit);
});
Iterating a string
let text = "Hello";
for (let char of text) {
console.log(char);
}
Live Example: Iterate through an array
Key Takeaways
forgives you full control over the indexfor...ofis simpler and clearer for arrays and stringsforEachis ideal for callback functions and more concise code
Control Statements: break and continue
In loops, you can control the execution flow with two special statements:
break— stops the loop entirelycontinue— skips the current iteration and moves to the next
Example with break
for (let i = 0; i < 10; i++) {
if (i === 5) {
break;
}
console.log("i is " + i);
}
// Stops when i reaches 5
Example with continue
for (let i = 0; i < 5; i++) {
if (i === 2) {
continue;
}
console.log("i is " + i);
}
// Skips 2, but continues with the rest
Filtering with break and continue
document.getElementById("filter").addEventListener("click", function () {
const list = document.getElementById("numberList");
list.innerHTML = "";
for (let i = 0; i < 10; i++) {
if (i === 7) break;
if (i % 2 === 0) continue;
const item = document.createElement("li");
item.textContent = "Odd number: " + i;
list.appendChild(item);
}
});
Key Takeaways
breakis useful when you want to stop a loop at a certain conditioncontinuehelps you skip special cases without stopping the loop- Use them carefully — overusing them can make code harder to follow
Nested Loops
A nested loop is a loop inside another loop. They are used when you want to traverse two-dimensional structures such as tables, matrices, or combinations of data.
Simple Example
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 2; j++) {
console.log("i = " + i + ", j = " + j);
}
}
The output will be:
i = 1, j = 1 i = 1, j = 2 i = 2, j = 1 i = 2, j = 2 i = 3, j = 1 i = 3, j = 2
Live Example: Coordinate Matrix
document.getElementById("generateCoordinates").addEventListener("click", function () {
const list = document.getElementById("coordinateList");
list.innerHTML = "";
for (let x = 1; x <= 3; x++) {
for (let y = 1; y <= 2; y++) {
const item = document.createElement("li");
item.textContent = "Coordinate: (" + x + ", " + y + ")";
list.appendChild(item);
}
}
});
Key Takeaways
- Each inner loop runs completely for every step of the outer loop
- You can have multiple nesting levels, but watch out for complexity
- Ideal for matrices, tables, data combinations, or grid generation