Functions
Function Declaration and Calling
A function is a way to group some code together and give it a name. Think of it like
creating a custom command that you can use later.
When JavaScript sees the function keyword, it knows that you are defining a new function.
Then it reads the name of the function, which is greet in this case.
The code inside the curly braces {} is the body of the function. This is the code that will
run when the function is called.
function greet() {
console.log("Hello, welcome to coding!");
console.log("You're inside the function now!");
}
greet();
greet();
// Without parentheses, the function doesn't run:
console.log(greet);
Key Points:
- Declare: Use
function name() { ... }to create a function - Call: Add parentheses
greet()to make the function run - Reuse: You can call the same function as many times as you want
- No parentheses - no call: Without
(), JavaScript sees the function itself, it does not execute it.
Parameters and Arguments
Sometimes you want a function to work with different information each time.
Parameters let you pass specific values into a function, making it flexible.
An argument is the real value you pass when you call the function.
In this example, we make pizza with different toppings. The topping parameter allows us to
specify the topping each time we call the function.
function makePizza(topping) {
console.log("Cooking a " + topping + " pizza...");
}
makePizza("Pepperoni");
makePizza("Mushroom");
const favouriteTopping = "Ham and Pineapple";
makePizza(favouriteTopping);
Key Points:
- Parameter: The placeholder input like topping inside the function
- Argument: The real value you pass, like
"Pepperoni"or a variable, like favouriteTopping - Reuse: One function can run many times with different inputs
- Common use case: run the same steps for different data
Return Values
When a function finishes its work, it can give you back a result using return keyword.
A return value is like a function's answer to a question you asked it.
You must store that result in a variable or use it right away on the same line of code.
If you ignore the result, it disappears.
A function without return gives back undefined.
function calculateTotal(price, tax) {
const total = price + tax;
return total;
}
const myBill = calculateTotal(100, 10);
console.log( calculateTotal(50, 5) );
calculateTotal(10, 1); // :x: return value is lost
function logTotal(price, tax) {
const total = price + tax;
console.log(total);
}
const noValue = logTotal(100, 10);
Key Points:
- Return value:
returnsends a result back to the caller - Capture it: Store the result in a variable like myBill
- Use inline: You can pass a return value straight into another call, like
console.log( calculateTotal(50, 5) ) - No return - undefined value: A function without
returngives backundefined. It's a common mistake to forget to return a value. - Common use case: calculate a number once and reuse it later
Multiple Returns
A function can have more than one return statement.
The first return that runs ends the function right away and sends back a value.
Any code below that return is ignored.
function checkAge(age) {
if (age < 18) {
return "Too young";
console.log("User's age is below 18!");
}
return "Welcome!";
}
const answer = checkAge(15);
console.log( checkAge(22) );
Key Points:
- Multiple paths: A function can have different return statements
- Early exit: The first return that runs ends the function
- Ignored code: Lines after a return in the same block never run
- Common use case: exit early when input is not valid, or when the result is already known
Scope Basics
Scope is about where variables "live" and where they can be used. A variable created in the main file is global and can be used in the code below its declaration. A variable created inside a function is local to that function and disappears when the function finishes.
let helloGlobalScope = "Hello, Global Scope";
function greet() {
console.log(helloGlobalScope);
const helloFunctionScope = "Hello, Function Scope";
console.log(helloFunctionScope);
helloGlobalScope = "Bonjour, Global Scope";
}
greet();
console.log(helloGlobalScope); // Works
console.log(helloFunctionScope); // ERROR!
Key Points:
- Global scope: Variables created outside functions can be used anywhere
- Function scope: Variables created inside a function only work there
- Lifetime: Local variables disappear when the function finishes
- Visisbility: Global code can't access function scope variables, but function can access and change global scope variables.
Function Expressions and Arrow Functions
Function expression is when you declare a function using the function
keyword and store it in a variable.
Arrow functions are a shorter way to write a function - without keyword
function and without an explicit name.
When function is in a variable you can call it by typing the variable name and parentheses.
// function expression - function stored in a variable
const multiply = function(a, b) {
return a * b;
};
const multResult = multiply(2, 5);
// arrow function with explicit return
const divide = (a, b) => {
const result = a / b;
return result;
};
console.log( divide(20, 4) );
// arrow function with implicit return
const square = (num) => num * num;
console.log( square(6) );
// arrow function without arguments
const sayMyName = () => console.log('Heisenberg');
sayMyName();
Key Points:
- Function expressions: Functions can live in variables like divide or multiply
- Arrow functions with implicit return: One-line arrows return the expression value automatically
- Arrow functions with explicit return: Multi-line arrows need a
returnstatement - Common use case: small helpers like math operations, logical conditions, accessing property values, or quick logging
Callback Functions
A callback function is a function you pass into another function to be run later.
The key idea: passing a function as an argument is not the same as calling it.
You pass the function name (like sumOperation), and the other function decides when to run
it.
function calculator(a, b, operation) {
const result = operation(a, b);
return result;
}
function add(x, y) {
return x + y;
}
const sum = calculator(1, 2, add);
const multiplication = (x, y) => x * y;
const product = calculator(5, 3, multiplication);
const diffence = calculator(10, 4, (x, y) => x - y);
Key Points:
- Callback: A function passed into another function to run later
- Pass vs call:
sumOperationpasses the function;sumOperation()would call it - Common use case: reuse one function and swap the behavior (add, multiply, filter)