Introduction
Welcome to Part 5 of the JavaScript for Beginners Series. In this part, we dive into Functions—blocks of code designed to perform specific tasks. We will explore the different ways to define them in modern JavaScript.
1. Function Declaration (The Classic Way)
This is the standard way to define a function. It uses the function keyword, a name, parentheses for parameters, and curly braces for the code block.
Structure:
function functionName(parameter1, parameter2) {
// code to be executed
return parameter1 + parameter2;
}
Example:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Karim"); // To run the function, you "call" it.
2. Function Expression
You can also define a function and assign it to a variable. This is useful because it allows you to treat functions like any other value (e.g., pass them to other functions).
Structure:
const variableName = function(parameter1, parameter2) {
// code to be executed
return parameter1 * parameter2;
};
Example:
const calculateArea = function(width, height) {
return width * height;
};
let area = calculateArea(10, 5); // Call the function via the variable.
console.log(area); // Outputs: 50
3. Arrow Functions (The Modern Way - ES6)
Arrow functions provide a shorter, more concise syntax for writing functions. They are extremely common in modern JavaScript codebases (especially in frameworks like React).
Structure:
const functionName = (param1, param2) => {
// more complex logic here
return param1 + param2;
};
Example:
const subtract = (a, b) => a - b; let difference = subtract(10, 4); console.log(difference); // Outputs: 6
Key Concepts Summary (بالدارجة)
Here is a summary of the most important concepts explained in Moroccan Darija:
- Function: دالة هي واحد الجزء من الكود عندو سمية، كيدير مهمة محددة، و كتقدر تعاود تستعملو وقتما بغيتي.
- Parameters: هي المتغيرات لي كتعرفها فالدالة باش تستقبل بيها المعلومات.
- Return Value: هي القيمة لي كترجعها الدالة من بعد ما كتسالي الخدمة ديالها باستعمال كلمة return.
- Types (الأنواع): كاينين طرق مختلفة باش تكتب دالة، أشهرها هي الطريقة العادية (function greet()) والطريقة العصرية والقصيرة (() => {}).
