Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aungthuoo/d4dd85a74d391fe04751bfac15b221d4 to your computer and use it in GitHub Desktop.
Save aungthuoo/d4dd85a74d391fe04751bfac15b221d4 to your computer and use it in GitHub Desktop.

Javascript 6 types of arrow functions {} => {}

1. No Parameters

if the function takes no parameters, you are empty parenthesis.

const greet = () => "Hello"; 
console.log(greet()); 

2. Single Parameters

If there's only on parameter, parentheses are optional.

const square = x => x * x; 
console.log(square(4)); 

3. Multiple Parameters

If there's only on parameter, parentheses are optional

const add = (a, b) => a + b; 
console.log( add(2, 3) ); 

4. Function Body with Multiple Statements

If the function body has more than one statement, you need to use curly braces and specify the return keyword (if you want to return something).

const greetPerson = name => {
  const greeting = "Hello, " + name + "!"; 
  return greeting;  
} 
console.log( greetPerson("Alice"));  

5. Returning Object Literials

When directly returning and object literal, wrap the literal in parentheses to differentiate it from the function block.

const makePerson = (firstName, lastName) => 
({ first: firstName, last: lastName });
console.log( makePerson("John", "Doe") );

// Outputs: { first: 'John', last: 'Doe'}

6. Higher Order Functions and Callbacks

Arraow functions are particularly popular when used as short callbacks.

const numbers = [1,2,3,4]; 
const doubled = numbers.map(num => num * 2); 
console.log(doubled); 

//Outputs: [2,4,6,8]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment