ā¤ Like
šŸ”– Save
šŸ”— Share
Eric Hu
Eric Hu

JavaScript Functions

@thedevspaceio

šŸ”§ 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:

js
function greet(name) {
  return `Hello, ${name}!`;
}
 
greet("Ada"); // "Hello, Ada!"

This also works:

js
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.

js
const add = function (a, b) {
  return a + b;
};
 
add(2, 3); // 5

Arrow functions

A shorter syntax for function expressions.

They do not have their own this keyword, making them ideal for small callbacks and functional patterns.

js
const multiply = (a, b) => a * b;
 
multiply(4, 5); // 20

Parameters and arguments

Functions can accept inputs called parameters. When calling a function, you provide arguments that correspond to those parameters.

js
function sayHello(greeting, name) {
  return `${greeting}, ${name}!`;
}
 
sayHello("Hi", "Grace"); // "Hi, Grace!"

Default parameters

Provide fallback values when an argument is undefined.

js
function greet(name = "Guest") {
  return `Hello, ${name}!`;
}
 
greet(); // "Hello, Guest!"
greet("Ada"); // "Hello, Ada!"

Rest parameters

Collect remaining arguments into an array.

js
function sum(...numbers) {
  return numbers.reduce((total, n) => total + n, 0);
}
 
sum(1, 2, 3, 4); // 10

Return values

Functions can return a value. Without a return statement, a function returns undefined.

js
function square(x) {
  return x * x;
}
 
square(5); // 25

Higher-order functions

Functions that accept other functions as arguments, or return functions as output are called higher-order functions.

js
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.

@thedevspaceio
www.thedevspace.io