JavaScript Function Cheat Sheet

JavaScript Function Cheat Sheet

Aung Kyaw Nyunt
Here's a comprehensive JavaScript Function Cheat Sheet that covers the essentials, common patterns, and key features related to functions in JavaScript:
ok. let's start the show. ;)
1. Function Declaration (Function Statement)
A function declaration defines a function with a specified name and can be called before it’s defined (due to hoisting).
function myFunction(param1, param2) { return param1 + param2; } console.log(myFunction(2, 3)); // 5
2. Function Expression
A function expression defines a function as part of a larger expression (it does not get hoisted).
const add = function(param1, param2) { return param1 + param2; }; console.log(add(2, 3)); // 5
3. Arrow Functions (ES6)
Arrow functions are a shorter syntax for writing functions. They also don’t have their own this context.
const add = (a, b) => a + b; console.log(add(2, 3)); // 5 const greet = name => `Hello, ${name}`; console.log(greet('Kevin')); // Hello, Kevin
  • No this binding: Arrow functions inherit the this value from the surrounding code.

  • No arguments object: They don’t have the arguments object, so for variable arguments, rest parameters should be used.
4. Function Parameters
Default Parameters

You can provide default values for function parameters.
function greet(name = 'Guest') { console.log(`Hello, ${name}`); } greet(); // Hello, Guest greet('Alice'); // Hello, Alice
Rest Parameters (...args)

Rest parameters allow you to represent an indefinite number of arguments as an array.
function sum(...args) { return args.reduce((acc, current) => acc + current, 0); } console.log(sum(1, 2, 3, 4)); // 10
Destructuring Parameters

You can use destructuring to extract values from objects or arrays in function parameters.
function greet({ name, age }) { console.log(`Hello, ${name}, you are ${age} years old.`); } greet({ name: 'Alice', age: 30 }); // Hello, Alice, you are 30 years old.
5. Function Scope
Global Scope vs Local Scope

  • Global Scope: Variables/functions declared outside of any function or block are in the global scope.

  • Local Scope: Variables declared inside a function are local to that function.
let globalVar = 'I am global'; // global scope function myFunc() { let localVar = 'I am local'; // local scope console.log(globalVar); // accessible console.log(localVar); // accessible } myFunc(); console.log(localVar); // Error: localVar is not defined
6. Hoisting
Function declarations are hoisted to the top, so you can call the function before it’s defined.
console.log(foo()); // 5 function foo() { return 5; }
However, function expressions are not hoisted:
console.log(bar()); // Error: bar is not a function var bar = function() { return 10; };
7. this Keyword
  • In regular functions, this refers to the object that called the function.

  • In arrow functions, this is lexically bound to the context in which the function was created (it does not create its own this).
// Regular function function regularFunc() { console.log(this); } const obj = { regularFunc }; obj.regularFunc(); // `this` refers to `obj` // Arrow function const arrowFunc = () => { console.log(this); }; arrowFunc(); // `this` refers to the surrounding context (global object or undefined in strict mode)
8. Callback Functions
A callback is a function passed into another function as an argument to be executed later.
function fetchData(callback) { setTimeout(() => { callback('Data fetched'); }, 2000); } fetchData((message) => { console.log(message); // Data fetched });
9. Immediately Invoked Function Expression (IIFE)
An IIFE is a function that runs as soon as it is defined.
(function() { console.log('I am executed immediately!'); })(); // I am executed immediately!
10. Closures
A closure is a function that "remembers" its lexical scope even when the function is executed outside that scope.
function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3
11. Recursion
A function that calls itself.
function factorial(n) { if (n === 0) return 1; return n * factorial(n - 1); } console.log(factorial(5)); // 120
12. Function Constructor
Functions can be created dynamically using the Function constructor.
const sum = new Function('a', 'b', 'return a + b'); console.log(sum(2, 3)); // 5
13. call(), apply(), and bind() Methods
  • call(): Invokes the function with a specified this context and arguments passed individually.
function greet() { console.log(`Hello, ${this.name}`); } const user = { name: 'Alice' }; greet.call(user); // Hello, Alice
  • apply(): Similar to call(), but arguments are passed as an array.
function greet(city, country) { console.log(`Hello, ${this.name} from ${city}, ${country}`); } greet.apply(user, ['Paris', 'France']); // Hello, Alice from Paris, France
  • bind(): Returns a new function with the this value set to the provided value and allows partial function application.
const greetAlice = greet.bind(user); greetAlice('Paris', 'France'); // Hello, Alice from Paris, France
14. Higher-Order Functions
A higher-order function is a function that either accepts a function as an argument or returns a function as its result.
function multiplyBy(factor) { return function(num) { return num * factor; }; } const multiplyBy2 = multiplyBy(2); console.log(multiplyBy2(5)); // 10
15. Function Expression vs Declaration
FeatureFunction DeclarationFunction Expression
Hoisting YesNo
Can be called before declarationYesNo
Syntaxfunction foo() {}const foo = function() {}
16. Function vs Arrow Function: Key Differences
Feature Regular Function Arrow Function
Syntax function() () => {}
this Binding Own this Lexical this
Arguments object Available Not available
17. Summary of Common Function Use Cases
  • Function Declaration: Define functions that are used across multiple parts of the code.

  • Function Expression: Used when you need to assign a function to a variable.

  • Arrow Functions: Ideal for callbacks and when you need to inherit this from the outer scope.

  • Closures: When you need a function to "remember" variables from an outer scope.

  • IIFE: Use when you want to run a function immediately after it's defined.
18. Final Words
JavaScript functions are extremely versatile and can be used in a wide variety of ways, from simple calculations to complex asynchronous operations. Understanding the different types of functions and their use cases will help you write more efficient and maintainable JavaScript code.
Happy Codding ;)
https://www.applix.info
© All right Reserved. Inspired Codes...
Get In Touch
Rule and Policy