
JavaScript Functions
š§ JavaScript Functions Cheatsheet
Functions in JavaScript aren't just blocks of code. They're values. They can be passed around, returned from other functions, and assigned to variables like strings or numbers.
This flexibility is what makes JavaScript so powerful, and so confusing if you don't understand how functions truly work.
I made this cheatsheet to clear things up. It covers the different ways to define functions, how to use parameters and arguments, and how to work with higher-order functions.
ā Function declarations ā Function expressions ā Arrow functions ā Parameters and arguments ā Default parameters ā Rest parameters ā Higher-order functions
#javascript #functions #scope #closures #higherorder #syntax #webdev #frontend #coding
Function declarations
A named function that is hoisted to the top of its scope. Meaning you can call it before its definition.
This works:
function greet(name) {
return `Hello, ${name}!`;
}
greet("Ada"); // "Hello, Ada!"This also works:
greet("Ada"); // "Hello, Ada!"
function greet(name) {
return `Hello, ${name}!`;
}Function expressions
A function assigned to a variable. It is not hoisted, and you must call it after its definition.
const add = function (a, b) {
return a + b;
};
add(2, 3); // 5Arrow functions
A shorter syntax for function expressions.
They do not have their own this keyword, making them ideal for small callbacks and functional patterns.
const multiply = (a, b) => a * b;
multiply(4, 5); // 20Parameters and arguments
Functions can accept inputs called parameters. When calling a function, you provide arguments that correspond to those parameters.
function sayHello(greeting, name) {
return `${greeting}, ${name}!`;
}
sayHello("Hi", "Grace"); // "Hi, Grace!"Default parameters
Provide fallback values when an argument is undefined.
function greet(name = "Guest") {
return `Hello, ${name}!`;
}
greet(); // "Hello, Guest!"
greet("Ada"); // "Hello, Ada!"Rest parameters
Collect remaining arguments into an array.
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
sum(1, 2, 3, 4); // 10Return values
Functions can return a value. Without a return statement, a function returns undefined.
function square(x) {
return x * x;
}
square(5); // 25Higher-order functions
Functions that accept other functions as arguments, or return functions as output are called higher-order functions.
function repeat(fn, times) {
for (let i = 0; i < times; i++) {
fn();
}
}
repeat(() => console.log("Hello"), 3);Full-Stack AI Developer Roadmap
From HTML & CSS to working with AI models, all in one structured roadmap.