|
| 1 | +// 📌 JavaScript Basics - Functions |
| 2 | + |
| 3 | +// Welcome to the fifth section of the JavaScript Basics tutorial! |
| 4 | +// Here, you'll learn how to declare and use functions in JavaScript. |
| 5 | + |
| 6 | +// Function Declaration (Named Function) |
| 7 | +function greet(name) { |
| 8 | + return "Hello, " + name + "!"; |
| 9 | +} |
| 10 | +console.log(greet("Alice")); |
| 11 | + |
| 12 | +// Function Expression (Anonymous Function) |
| 13 | +const add = function (a, b) { |
| 14 | + return a + b; |
| 15 | +}; |
| 16 | +console.log("Sum:", add(5, 3)); |
| 17 | + |
| 18 | +// Arrow Function (ES6+) |
| 19 | +const multiply = (x, y) => x * y; |
| 20 | +console.log("Multiplication:", multiply(4, 2)); |
| 21 | + |
| 22 | +// Default Parameters |
| 23 | +function sayHello(name = "Guest") { |
| 24 | + console.log("Hello, " + name); |
| 25 | +} |
| 26 | +sayHello(); |
| 27 | + |
| 28 | +// Rest Parameters |
| 29 | +function sumAll(...numbers) { |
| 30 | + return numbers.reduce((total, num) => total + num, 0); |
| 31 | +} |
| 32 | +console.log("Total Sum:", sumAll(1, 2, 3, 4, 5)); |
| 33 | + |
| 34 | +// Callback Functions |
| 35 | +function processArray(arr, callback) { |
| 36 | + return arr.map(callback); |
| 37 | +} |
| 38 | +const numbers = [1, 2, 3, 4]; |
| 39 | +const doubled = processArray(numbers, (num) => num * 2); |
| 40 | +console.log("Doubled Array:", doubled); |
| 41 | + |
| 42 | +// 💡 Practice writing different types of functions! |
0 commit comments