JS Functions
Function Study Path
To learn functions efficiently: start with function basics, then parameters and return values, then expressions and arrow functions. Finally, learn callbacks and common patterns.
Function Intro
A function is a reusable block of code. It can take inputs (parameters) and produce an output (return value).
function greet() {
console.log("Hello!");
}
greet();
Function Invocation
Invoking (calling) a function means running its code. You call a function using parentheses ().
function sayHi(name) {
console.log("Hi, " + name);
}
sayHi("Ozan");
Function Parameters
Parameters are variables listed in the function definition. They receive values when the function is called.
function add(a, b) {
console.log(a + b);
}
add(5, 7);
Default parameters provide a fallback value when an argument is missing.
function welcome(name = "Guest") {
return "Welcome, " + name;
}
console.log(welcome());
console.log(welcome("John"));
Function Returns
return sends a value back to the caller. When a function returns, it stops executing.
function multiply(a, b) {
return a * b;
}
let result = multiply(3, 4);
console.log(result);
Function Arguments
Arguments are the actual values passed to the function when it is called.
function showUser(name, age) {
console.log(name, age);
}
showUser("Jane", 28); // "Jane" and 28 are arguments
Rest parameters collect multiple arguments into an array.
function sumAll(...nums) {
let total = 0;
for (const n of nums) {
total += n;
}
return total;
}
console.log(sumAll(1, 2, 3, 4));
Function Expressions
A function expression stores a function inside a variable. This is common when passing functions as values.
const square = function (n) {
return n * n;
};
console.log(square(5));
Immediately Invoked Function Expressions (IIFE) run once immediately.
(function () {
console.log("Runs once");
})();
Function Arrow
Arrow functions provide a shorter syntax. They are often used for callbacks.
const add = (a, b) => a + b; console.log(add(2, 3));
With one parameter, parentheses are optional. With zero or multiple parameters, parentheses are required.
const double = n => n * 2; const now = () => Date.now(); console.log(double(10)); console.log(now());
Callbacks (Modern Must-Know)
A callback is a function passed into another function to be called later.
function runTask(task) {
task();
}
runTask(() => {
console.log("Task completed");
});
Hoisting Note
Function declarations are hoisted (they can be called before they appear in the code). Function expressions are not hoisted in the same way.
hello(); // works
function hello() {
console.log("Hello");
}
// hi(); // Error
const hi = function () {
console.log("Hi");
};
Next Step
Continue with JS Objects to learn how JavaScript organizes data using key-value pairs.