Lesson 20: Functions
π§© Lesson 20: JavaScript Functions
Functions are like machines in your code. You give them input (called parameters) and they give you output (via return). You can call them over and over again.
π¦ Function Declaration
This is the most classic way to define a function.
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Joe")); // Hello, Joe!
π‘ Function Expression
You can store a function in a variable. This is called a function expression.
const add = function (a, b) {
return a + b;
};
console.log(add(2, 3)); // 5
β‘ Arrow Functions
Arrow functions are shorter and neater. Great for quick logic, especially in callbacks.
// Basic version
const sayHi = (name) => {
return "Hi " + name;
};
// Even shorter if one-line
const double = x => x * 2;
console.log(sayHi("Ada")); // Hi Ada
console.log(double(4)); // 8
πΆ Anonymous Functions
Functions without a name. Often used as callbacks.
setTimeout(function () {
console.log("Hello after 2 seconds");
}, 2000);
βοΈ IIFE (Immediately Invoked Function Expression)
A function that runs immediately after itβs defined. Wrapped in parentheses.
(function () {
console.log("I run immediately!");
})();
π Callback Functions
Passing a function as an argument to another function. Powerful for async logic, events, etc.
function processUserInput(callback) {
const name = "Joe";
callback(name);
}
processUserInput(function (name) {
console.log("Welcome, " + name);
});
π§ Parameters vs Arguments
- Parameters are like placeholders (in the function)
- Arguments are the actual values you pass in
π οΈ Default Parameters
You can give parameters a default value in case none is passed.
function greet(name = "friend") {
return "Hello, " + name;
}
console.log(greet()); // Hello, friend
console.log(greet("Joe")); // Hello, Joe
π Returning vs Not Returning
Use return to send a result back. If you donβt use it, the function returns undefined.
function add(a, b) {
return a + b;
}
function logSum(a, b) {
console.log(a + b);
}
console.log(add(2, 3)); // 5
console.log(logSum(2, 3)); // Logs 5, but returns undefined
π Summary
- Use function to define reusable logic
- Arrow functions are shorter and neater
- Functions can take parameters and return results
- They can be named or anonymous
- Use IIFE to run logic instantly
- Functions can be passed as arguments (callbacks)
Functions are the building blocks of logic. In the next lesson, weβll dive into Selecting Elements in the DOM, the fun part of using Javascript with HTML and CSS.