ā¤ Like
šŸ”– Save
šŸ”— Share
@thedevspaceio
@thedevspaceio

JavaScript Functions Cheatsheet

@thedevspaceio

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

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