JavaScript Functions Cheatsheet
š§ JavaScript Functions Cheatsheet
Functions are blocks of code assigned to a value, which can be reused elsewhere in the program. They can accept inputs, return outputs, and be passed around like any other value.
ā 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.