🌱BeginnerFunctions
Functions
Declaring, calling, and composing functions the foundation of reusable code.
Overview
A function is a named, reusable block of code. Instead of copying and pasting the same logic, you write it once in a function and call it whenever needed. Functions are first-class citizens in JavaScript they can be stored in variables, passed as arguments, and returned from other functions.
There are two classic ways to define a function: a function declaration and a function expression. Declarations are hoisted you can call them before the line where they are defined in the file. Expressions assigned to a const are not hoisted.
Functions accept parameters (the named placeholders in the definition) and receive arguments (the actual values passed when called). Every function returns a value if you omit return, the function returns undefined. Parameters can have default values, making the argument optional at the call site.
Key Points
- •function declaration: function name() {} hoisted, callable before definition
- •function expression: const name = function() {} not hoisted
- •Parameters are the variables listed in the definition; arguments are the values passed in
- •Default parameters: function greet(name = "World") used when argument is omitted or undefined
- •Every function returns undefined unless you explicitly return a value
- •Functions can return any value, including other functions
Examples
Declaration vs expression, parameters, return
// Declaration (hoisted)
function add(a, b) {
return a + b;
}
console.log(add(3, 4)); // 7
// Expression (not hoisted)
const multiply = function(a, b) {
return a * b;
};
console.log(multiply(3, 4)); // 12Default parameters and optional arguments
function greet(name = "World", greeting = "Hello") {
return `${greeting}, ${name}!`;
}
console.log(greet()); // Hello, World!
console.log(greet("Alice")); // Hello, Alice!
console.log(greet("Bob", "Hi")); // Hi, Bob!Functions as values first-class citizens
function applyTwice(fn, value) {
return fn(fn(value));
}
function double(x) {
return x * 2;
}
console.log(applyTwice(double, 3)); // 12 (3 → 6 → 12)Passing a function as an argument is called a callback. It's fundamental to arrays, events, and async code.
Common Mistakes
- Calling a function without () greet logs the function itself, greet() calls it
- Forgetting return the function implicitly returns undefined
- Relying on hoisting for function expressions only declarations are hoisted
Exercises
Write JavaScript code to solve each exercise. Run it and check your output.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4